Probability in Java

前端 未结 5 711
借酒劲吻你
借酒劲吻你 2020-12-04 21:57

I was curious to know, how do I implement probability in Java? For example, if the chances of a variable showing is 1/25, then how would I implement that? Or any other proba

5条回答
  •  忘掉有多难
    2020-12-04 22:21

    Generally you use a random number generator. Most of those return a number in the interval [0,1] so you would then check whether that number is <= 0.04 or not.

    if( new Random().nextDouble() <= 0.04 ) {  //you might want to cache the Random instance
       //we hit the 1/25 ( 4% ) case.
    }
    

    Or

    if( Math.random() <= 0.04 ) {
      //we hit the 1/25 ( 4% ) case.
    }
    

    Note that there are multiple random number generators that have different properties, but for simple applications the Random class should be sufficient.

提交回复
热议问题