您的位置:首页 > 其它

数学问题——调整概率

2018-03-31 22:00 351 查看

调整概率

调整[0,x)区间上的数出现的概率

【题目】

假设函数Math.random()等概率随机返回一个在[0,1)范围上的

数,那么我们知道,在[0,x)区间上的数出现的概率为x

(0 < x ≤ 1)。给定一个大于0的整数k,并且可以使用

Math.random()函数,请实现一个函数依然返回在[0,1)范围上

的数,但是在[0,x)区间上的数出现的概率为xk(0 < x ≤ 1)。

public class ProbabilityXPowerK {

public static double randXPower2() {
return Math.max(Math.random(), Math.random());
}

public static double randXPowerK(int k) {
if (k < 1) {
return 0;
}
double res = -1;
for (int i = 0; i != k; i++) {
res = Math.max(res, Math.random());
}
return res;
}

public static void main(String[] args) {
double range = 0.5;
int times = 5000000;
int count = 0;
for (int i = 0; i != times; i++) {
if (randXPowerK(2) < range) {
count++;
}
}
double p = (double) count / (double) times;//统计小于某概率的次数除以总次数
System.out.println("range [0," + range + "), probability: " + p);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: