このプログラムの目標は、分数に対して 2 つの確率変数を取り、それらが既に簡約されているかどうかを確認することです。これの推定確率は 6/(pi^2) です。1,000 種類の変数の組み合わせを実行し、削減された変数と削減されなかった変数の数を特定します。それから私は円周率を解きます。
しかし、実行するたびに「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); }
}