概率命中算法

kakai 发布于 2014/07/16 11:33

```public static boolean isHitProbability(float rate, int total) {
if(rate == total) {
return true;
}
float m = rate % 1;
if (m != 0) {
String str = String.valueOf(rate);
String v = str.split("\\.")[1];
int len = v.length();
double cen = Math.pow(10, len);
rate *= cen;
total *= cen;
}
int hitValue = new Random().nextInt(total) + 1;
return hitValue <= (int) rate;
}```
`isHitProbability(20,100),返回true表示概率命中成功 `
`isHitProbability(0.5f,100),返回true表示概率命中成功 `

1

0

String v = str.split(".")[1];

String v = str.split("\\.")[1];

0
public static boolean isHitProbability(float rate, int total) {
if(rate == total) {
return true;
}
float m = rate % 1;
if (m != 0) {
String str = String.valueOf(rate);
String v = str.split("\\.")[1];
int len = v.length();
double cen = Math.pow(10, len);
rate *= cen;
total *= cen;
}
int hitValue = new Random().nextInt(total) + 1;
return hitValue <= (int) rate;
}
0
k

0
random(1,  total) <= rate
random(1, total)这个是哪个里面的？Random类里没有吧，Math.random更加没有了
0

public static boolean isHitProbability(int rate, int total) {
if (total == rate) {
return true;
}
if (rate < 0) {
return false;
}
if (total < rate) {
return false;
}
return new Random().nextInt((int) (total / rate)) == 0;
}

0
k
```//random不用考虑并发
static Random r = new Random();

/**
*
* probs 为一系列的概率值 且合为1
* @param probs
* @return 命中的内容的index
*/
static int cal(double[] probs){
double s = r.nextDouble();
double carry = 0.0;
for(int i=0;i<probs.length;i++){
carry+=probs[i];
if(carry>=s) return i;
}
return probs.length-1;
}```