该程序的目标是取 2 个随机变量作为分数,看看它们是否已经在缩减项中。假设的概率是 6/(pi^2)。我运行了 1,000 种不同的变量组合,并确定有多少已经减少和尚未减少。然后我求解 pi。
但是每次我运行它时,输出都会给我“pi is 2.449489742783178”。
有谁知道为什么?谢谢。
import java.util.*;
public class ratio1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int nonReducedCount = 0; //counts how many non reduced ratios there are
for(int i =1; i<=1000; i++){
Random rand = new Random();
int n = rand.nextInt(1000)+1; //random int creation
int m = rand.nextInt(1000)+1;
//Ratio ratio = new Ratio(n,m);
if (gcd(n,m)> 1 ){ // if the ratio was not already fully reduced
nonReducedCount++; // increase the count of non reduced ratios
}
}
int reducedCount = 1000 - nonReducedCount; //number of times the ratio was reduced already
double reducedRatio = reducedCount / nonReducedCount; //the ratio for reduced and not reduced
reducedRatio *= 6;
reducedRatio = Math.sqrt(reducedRatio);
System.out.println("pi is " + reducedRatio);
}
public static int gcd(int a, int b) { return b==0 ? a : gcd(b,a%b); }
}