关于Java中的Math.random()函数

Math.random()

关于Java中的Math.random()函数大家应该都不陌生,调用后,会等概率的返回[0,1)之间double类型的小数。
为什么会说是等概率的数呢?来,让我们测试一下

 		int testTime = 1000000;
        int count = 0;
        for (int i = 0; i < testTime; i++) {
            if (Math.random() < 0.25){
                count++;
            }
        }
        System.out.println((double)count / (double)testTime);

一共测试testTime次,如果< 0.25则count++,最后再用count次数 / testTime,就是Math.random中 < 0.25的次数。
那么Math.random * K,是否也是等概率的返回。

 		int testTime = 1000000;
        int[] counts = new int[8];
        for (int i = 0; i < testTime; i++) {
            int index = (int)( Math.random() * 8);
            counts[index]++;
        }

        for (int j = 0; j < counts.length; j++) {
            System.out.println(counts[j]);
        }

假设K = 8,经过测试发现,Math.random * 8,会等概率的返回(0,8]之间的数。

经过之前的测试发现,每次Math.random()函数,返回(0,X]之间的数的概率,都是X

那么,该如何让 (0,X] 之间返回的数,是之前的平方呢?

		int testTime = 1000000;
        int count = 0;
        double x = 0.3;
        //(0,x]
        for (int i = 0; i < testTime; i++) {

            if (Math.max(Math.random(),Math.random())< x){
                count ++;
            }
        }

        System.out.println((double) count / (double) testTime);
        System.out.println(Math.pow(x,2));

调用一次Math.max,并在其中调用两次Math.random()函数,取两次Math.random方法中返回的最大值,那么如果任意两次返回结果 > x,都是无效的,只有两次的返回都 < 0.3 count才可以++, 那么就是x的平方。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值