java - math.Random 无法正常工作

标签 java math random

我正在尝试使用下面的代码来模拟抛硬币。

public class Coin
{
    public static double result;
        int[] count = new count[2];

    public static void flip()
    {       
        result = Math.random();
    }

        public static boolean isHeads()
        {
        if (result == 0.0)
        {
                    count[0]++;
            return false;
        }

        else
        {
                    count[1]++;
            return true;
        }
        }

        public static void main(String[] args)
        {
             flip();
             isHeads();
             System.out.println(count[0]);
             System.out.println(count[1]);
        }
}

由于某种原因 Eclipse 说

导入java.util.Random;

从未被使用过,尽管我明显在使用它。我没有将 for 循环放入上面的代码中,但它循环了 n 次,然后输出结果。无论循环多少次,它总是返回结果大于 0.0,这是不正确的。我是否错误地调用了 Math.random?

最佳答案

您正在使用 Math,它可能正在使用 Random,但您没有在任何地方使用 Random。

No matter how many times it loops it always returns that the result is greater than 0.0 which can't be right. Am I calling Math.random incorrectly?

0.0 到 1.0 之间有 2 ^ 53 个可能的值,并且由于 Random 仅使用 48 位种子,因此您可能会生成它将创建的每个 double 并且不会出现任何值。如果您使用 SecureRandom,您有二分之一^ 53 的机会返回 0.0。

关于java - math.Random 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12533668/

相关文章:

java - 如何运行多模块maven应用程序?

java - 使用fragmentTransaction.replace时会替换哪个Fragment?

c++ - 从弧度转换为度数

c - 对于我们在 C 中使用 time(NULL) 来生成 =random 值

Java Collections.shuffle() 奇怪的行为

java - 鼠标事件 "cannot find symbol"错误的解决方案

Java同步帮助请求

python - 如何快速估计两个(纬度、经度)点之间的距离?

compression - 为什么我可以将 "fold"范围内的整数变成二分之一大小而不丢失信息?

windows - CryptGen随机熵