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
 

Pinhedd

Distinguished
Moderator


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"