《程序员代码面试指南》调整[0,x)区间上的数出现的概率——java实现

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

题目描述:

假设函数Math.random()等概率随机返回一个在[0,1)范围上的数,那么我们知道,在[0,x)区间上的数出现的概率为x (0 给定一个大于0的整数k,并且可以使用 Math.random()函数,请实现一个函数依然返回在[0,1)范围上的数,但是在[0,x)区间上的数出现的概率为x的k次方(0

题目难度:

easy

题目思路:

本题给定一个x和k,要求出一个数出现在(0——x)范围的概率为x的k次方。
思路如下:
要求出一个数出现在(0——x)范围的概率为x的k次方,即使用Math.random()函数计算k次,求出这k次中最大的值,使该最大值小于给定x即可。

代码实现:

/**
 * Created by Zhaoyang Ge on 2018/11/2.
 */
public class ProbabilityXPowerK {
    public static double randXPower2() {   //计算在0——x范围内,出现x平方次的概率
        return Math.max(Math.random(), Math.random());
    }

    public static double randXPowerK(int k){
        if (k == 1){
            return 0;
        }
        double res = 0;
        for (int i = k; i > 0; i--){
            res = Math.max(res, Math.random()); //计算k次,保证每次取到的值都在要求范围内,则此时是x的k次方
        }
        return res;
    }

    public static void main(String[] args) {
        double range = 0.7;
        int count  = 0;
        int times = 500000;
        for (int i = 0; i < times; i++){
            if (randXPowerK(2) < range){ // 满足所求出的值在(0, range)范围内即可
                count++;
            }
        }
        double p = (double) count / (double)times;
        System.out.println("range [0," + range + "), probability: " + p);
    }

}

你可能感兴趣的:(左神)