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

来源:互联网 发布:网络整合营销理论4i 编辑:程序博客网 时间:2024/06/14 00:26

【题目】

函数Math.random()等概率随即返回一个在[0,1)范围上的 数,即在[0,x)区间的数出现的概率为x(0<x≤1)
给定一个大于0的整数k,使用Math.random(), 实现返回在[0,1)上的数,但在[0,x)区间的数出现的概率为x^k (0<x≤1)

【解答】

只用调用k次Math.random(),返回最大的那个数即可

【代码】

//交换两个整数的值    public static void change(int a,int b){        a=a+b-(b=a);        System.out.println(a);        System.out.println(b);    }    //调整[0,x)区间上的数出现的概率    public static double randPowerK(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;    }
阅读全文
0 0