使用蒙特卡罗方法在pi值中输出错误



我试着用蒙特卡罗方法(不使用任何可视化(制作一个JAVA程序来计算圆周率的值,我觉得一切都很好,但每当我运行它时,答案总是0.0。我不知道出了什么问题,请帮我。

这是代码:

import java.util.*;
// Compiler version JDK 11.0.2
class PiMonteCarlo{
public static void main(String args[]){ 
Random rand =new Random();
double r=1.0;
int cir=0,sq=0,range=200+1,min=0;
for(int i=1;i<=200000;i++){
double y = rand.nextDouble();
double x = rand.nextDouble();
double d=(x*x)+(y*y);
if(d<=r){
cir++;
}
sq++;
}
double rat=cir/sq;
System.out.print(4*rat);
}
}

欢迎来到stackoverflow。

问题是,你需要大量的迭代才能很好地估计π。

使用4.0进行双除法,而不是4。

import java.util.*;
class PiMonteCarlo{
public static void main(String args[]){
double radius = 1;
Random random = new Random();
int inside = 0;
int trials = 10^100000000;
for(int i = 1; i<=trials; i++){
double y = random.nextDouble();
double x = random.nextDouble();
if((x*x)+(y*y) <= radius){
inside++;
}
}
double rat = 4.0 * inside/trials;
System.out.print(rat);
}
}

cir/sq是整数除法。尝试:

double rat = (double)cir / sq;

最新更新