其他替代方案使得rand.nextDouble()beetwen -1和1

naz*_*art 1 java random

这个简单的程序程序通过模拟投掷到正方形上的投掷来计算pi的估计.

Сonditions:生成一个随机浮点数并对其进行转换,使其介于-1和1之间.
存储在x中.重复y.检查(x,y)是否在单位圆中,即(0,0)和(x,y)之间的距离<= 1.

在此之后,需要找到与ratio hits / tries比例大致相同的值circle area / square area = pi / 4.(方形是每1 1).

码:

public class MonteCarlo {
    public static void main(String[] args) 
    {
        System.out.println("Number of tries");
        Random generator = new Random(42);
        Scanner in = new Scanner(System.in);
        int tries = in.nextInt();

        int hits = 0;
        double x, y;
        for (int i = 1; i <= tries; i++)
        {
            // Generate two random numbers between -1 and 1            
            int plusOrMinus = generator.nextInt(1000);
            if (plusOrMinus > 500) x = generator.nextDouble();                
            else x = -generator.nextDouble();

            plusOrMinus = generator.nextInt(10000);
            if (plusOrMinus > 5000) y = generator.nextDouble(); 
            else y = -generator.nextDouble();             

            if (Math.sqrt((x * x) + (y * y)) <= 1) // Check whether the point lies in the unit circle
            {
                hits++;
            }
        }

        double piEstimate = 4.0 * hits / tries;
        System.out.println("Estimate for pi: " + piEstimate);
    }
}
Run Code Online (Sandbox Code Playgroud)

测试输出:

  Actual output            Expected output
  -----------------------------------------------
  Number of tries          Number of tries
  1000                     1000
- Estimate for pi: 3.176   Estimate for pi: 3.312

  Actual output               Expected output
  -----------------------------------------------------
  Number of tries             Number of tries
  1000000                     1000000
- Estimate for pi: 3.141912   Estimate for pi: 3.143472
Run Code Online (Sandbox Code Playgroud)

也许,确实存在其他寻找此解决方案的方法吗?有什么建议.

Mat*_*ias 6

要生成-1和1之间的随机双精度,请尝试:

generator.nextDouble() * 2 - 1
Run Code Online (Sandbox Code Playgroud)

顺便说一句:如果你用静态种子初始化你的随机数,你总会得到相同的结果.否则,如果您担心结果不够好,请记住蒙特卡洛只是一个近似值.毕竟,它基于随机数,因此结果与样本解决方案不同;-)