0
這個程序的目標是對一個分數取2個隨機變量,看看它們是否已經減少了。假設的可能性是6 /(pi^2)。我運行了1000個不同的變量組合,並確定有多少個並沒有減少。然後我解決pi。程序每次都應該是隨機的時候會給出相同的結果
但是每次運行它時,輸出結果都是「pi 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); }
}
啊謝謝!有效! –