使用 monte carlo 方法输出 pi 值错误
Wrong output in pi value using monte carlo method
我尝试制作一个 JAVA 程序来使用 monte carlo 方法计算 pi 的值(不使用任何可视化)对我来说一切似乎都很好但是每当我 运行 它时,答案总是 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);
}
}
cir / sq 为整数除法。尝试:
double rat = (double)cir / sq;
欢迎使用 Whosebug。
问题是,您需要大量迭代才能很好地估计 pi。
使用 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);
}
}
我尝试制作一个 JAVA 程序来使用 monte carlo 方法计算 pi 的值(不使用任何可视化)对我来说一切似乎都很好但是每当我 运行 它时,答案总是 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);
}
}
cir / sq 为整数除法。尝试:
double rat = (double)cir / sq;
欢迎使用 Whosebug。
问题是,您需要大量迭代才能很好地估计 pi。
使用 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);
}
}