我必须使用蒙特卡罗方法来计算圆周率。需要获取(-1,1)之间的xy坐标。然而,每次我运行该程序时,它都会给出 0 的答案。我不确定我做错了什么,有人可以帮忙吗?
package montecarlo;
import java.util.Scanner;
import java.io.PrintStream;
import java.util.Random;
public class MonteCarlo {
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter total number of dart throws");
int nThrows = keyboard.nextInt();
double PI= calculatePi(nThrows);
PrintStream ps = new PrintStream("PiEstimate.txt");
ps.printf("PI estimate = %.4f", PI);
}
public static boolean insideCircle (double x, double y)
{
double range = Math.sqrt((x * x) + (y * y));
return (range < 1.0);
}
public static double calculatePi(int nThrows)
{
int dartsInCircle = 0;
double piEstimate;
Random rGenerator = new Random();
for (int i=0; i < nThrows; i++) {
double x = rGenerator.nextDouble()*Math.pow(-1, rGenerator.nextInt());
double y = rGenerator.nextDouble()*Math.pow(-1, rGenerator.nextInt());
if (insideCircle(x,y))
dartsInCircle++;
} piEstimate=(4.0*(dartsInCircle/nThrows));
return piEstimate;
}
}
最佳答案
您在这里将 int
除以 int
:(dartsInCircle/nThrows)
。
由于 dartsInCircle
始终小于 nThrows
,因此整数除法将始终返回 0
。您需要将其中一个操作数转换为双倍。
编辑:如果您使用足够好的 IDE(例如 IntelliJ),它应该会提示您“精度损失”警告或类似警告。
关于java - 使用蒙特卡罗方法计算 pi java - 计算不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46762938/