How to compute PI

Liang Cao

Estimable
Mar 23, 2015
1
0
4,510
0
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"
 
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
 
Thread starter Similar threads Forum Replies Date
Zugoldragon Apps General Discussion 2
S Apps General Discussion 1
P Apps General Discussion 5
A Apps General Discussion 5
H Apps General Discussion 2
P Apps General Discussion 1
T Apps General Discussion 1
K Apps General Discussion 2
R Apps General Discussion 4
M Apps General Discussion 1
R Apps General Discussion 1
H Apps General Discussion 4
K Apps General Discussion 6
G Apps General Discussion 1
F Apps General Discussion 1
T Apps General Discussion 1
A Apps General Discussion 1
T Apps General Discussion 1
O Apps General Discussion 1
M Apps General Discussion 5

ASK THE COMMUNITY