# How to compute PI

#### Liang Cao

##### Estimable
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

#### Someone Somewhere

##### Dignified
Moderator
I think you're having issues with integer rounding - it's dividing an integer by an integer, so won't do floating point math.

Try using 4.0 instead of 4.

#### Alabalcho

##### Judicious
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.

#### 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"

#### Alabalcho

##### Judicious
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

Apps General Discussion 2
Apps General Discussion 1
Apps General Discussion 5
Apps General Discussion 5
Apps General Discussion 2
Apps General Discussion 1
Apps General Discussion 1
Apps General Discussion 2
Apps General Discussion 4
Apps General Discussion 1
Apps General Discussion 1
Apps General Discussion 4
Apps General Discussion 6
Apps General Discussion 1
Apps General Discussion 1
Apps General Discussion 1
Apps General Discussion 1
Apps General Discussion 1
Apps General Discussion 1
Apps General Discussion 5