gpt4 book ai didi

java - 简单java中Pi的蒙特卡洛模拟?

转载 作者:行者123 更新时间:2023-11-30 09:04:12 24 4
gpt4 key购买 nike

我正在尝试进行著名的蒙特卡洛模拟来估算我的 Java 类(class)的圆周率。这是模拟:

 public class Darts
{
//"throwing" a dart
public static boolean [] dartThrow(int r, int d){
boolean [] booleanArray = new boolean[d];
for(int i = 0; i < d; i++){
double xCoord = Math.random() * 2;
double yCoord = Math.random() * 2;
if((Math.pow(xCoord,2) + Math.pow(yCoord,2)) <= r){
booleanArray[i] = true;
}
else{
booleanArray [i] = false;
}
}
return booleanArray;
}

//calculating pi from throwing results
public static double piEstimater(boolean [] h, int d){
int trueCounter = 0;
for(int i = 0; i < h.length; i++){
if(h[i] == true){
trueCounter++;
}
}
return 4 * ((double)trueCounter / d);
}

//printing results
public static void printer(double [] a){
System.out.println(" Pi Estimation Tool ");
System.out.println("---------------------------");
for(int i = 0; i < a.length; i++){
System.out.print("Trial [" + i + "]: pi = ");
System.out.printf("%6f\n", a[i]);
}
}

public static void main(String[] args){
//variables
Scanner in = new Scanner(System.in);
int radius = 1;
int darts;
int trials;

System.out.println("Enter the number of darts to calculate for: ");
darts = in.nextInt();
System.out.println("Enter the number of trials to calculate for: ");
trials = in.nextInt();

double [] arrayOfEstimates = new double [trials];
int i = 0;
for(double a : arrayOfEstimates){
boolean [] hitCounter = dartThrow(radius, darts);
double piEstimate = piEstimater(hitCounter, darts);
arrayOfEstimates[i] = piEstimate;
i++;
}

printer(arrayOfEstimates);
}
}

我已经创建了可以正确执行的代码,除了结果永远不会超过 ~ .8。我想假设这是因为随机数太低而发生,但如果每次都发生这种情况就一定是错误的,对吧?请记住,这段代码包含了我所知道的所有 Java 技术,所以如果您不包含任何更“高级”的内容,我将不胜感激。谢谢!

最佳答案

使用蒙特卡洛方法计算 PI 的思想是在一个正方形中随机采样点,并计算它们落在该正方形所包围的圆面积内的分数。如果有足够多的点被均匀采样,分数将接近于圆的面积除以边界正方形的面积:

fraction = PI*r^2/(2r)^2

因此

PI = fraction * 4 .

现在,由于您仅对正坐标进行采样,如果我们假设圆的中心位于原点 (0,0) ,我们只对圆的右上四分之一及其边界正方形内的点进行采样,但等式保持不变。

如果你的圆的半径为 r,你应该在 0 和 r 之间采样坐标。

因此你应该改变这个:

    double xCoord = Math.random() * 2;
double yCoord = Math.random() * 2;

为此:

    double xCoord = Math.random() * r;
double yCoord = Math.random() * r;

另外条件应该是((Math.pow(xCoord,2) + Math.pow(yCoord,2)) <= r*r) .

当然,你可以通过消去r并假设半径为1来简化它。

在这种情况下,条件将是 ((Math.pow(xCoord,2) + Math.pow(yCoord,2)) <= 1)并且坐标将在 0 和 1 之间采样。

关于java - 简单java中Pi的蒙特卡洛模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25346042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com