How to compute PI

Liang Cao

Estimable
Mar 23, 2015
1
0
4,510
Code:
public class ComputePI {
	public static void main(String args[]){
		double sum = 0.0;
		int maxDemo = 10000000;
		
		for (int denom = 1; denom < maxDemo; denom= denom + 2 ){
			if (denom%4 == 1){
				sum += (double) (4/denom);
			} else if (denom%4 ==3){
				sum -= (double)(4/denom);
			} else {
				System.out.println("The system has gone crazy");
			}
		}
		System.out.println("PI is " + sum);
       }
}

My output is : PI is 3.0
The correct ans should be 3.141592653589793

Code tags added - SS
 
Just a note on the algorithm used: As you probably know, PI is irrational number, so any number of digits will be just a close value of PI, never full value, so there is no "correct" answer.
 


This is correct. The typecast is applied after the division. Type denom as a float (this is fine since it's never a fraction so the equality won't fail) or type the literal as a float "4.0f"
 
One more note about precision. Last term to be applied to above sum will be 4.0/9,999,999. This will affect seventh digit after the decimal point, and the result will have only six correct digits - far away from the target of 3.141592653589793