When you divide two integers, you get integer division, with an integer result, even if you later assign the result to a double
. Try
double reducedRatio = (double)reducedCount / nonReducedCount;
i.e. convert one of the operands to a double
.
Question
The goal of this program is to take 2 random variables for a fraction and see if they are already in reduced terms or not. The supposed probability of this is 6/(pi^2). I run 1,000 different combinations of variables and determine how many were and were not already reduced. Then I solve for pi.
But the output is giving me "pi is 2.449489742783178" every time I run it.
Anyone know why? Thanks.
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); }
}
Solution
When you divide two integers, you get integer division, with an integer result, even if you later assign the result to a double
. Try
double reducedRatio = (double)reducedCount / nonReducedCount;
i.e. convert one of the operands to a double
.