programer310 programer310 - 10 days ago 5
Java Question

Java For-loop changes numeric result when changing type of loop variable

I wrote a program to calculate the PI number with Leibniz formula:

[Leibniz formula]

I wrote a for-loop with type of initialization is "int" , the loop works fine but when i changed the initialization type to "long" the result is changed. This only happens when the loop times over a billion. This makes the "int - loop" calculates PI more accurate than "long - loop". I don't know why this happens. Please help me to understand this issue. Thanks! and here is my code.

public static void main(String[] args) {
double result1 = 0;
double result2 = 0;
double sign = 1;

for (int i = 0; i <= 1607702095; i++) {
result1 += sign/(2 * i + 1);
sign *= -1;
}
sign = 1;

for (long j = 0; j <= 1607702095; j++) {
result2 += sign/(2 * j + 1);
sign *= -1;
}

System.out.println("result1 " + result1 * 4);
System.out.println("result2 " + result2 * 4);
System.out.println("pi " + Math.PI);
}


And the result is:

result1 3.141592653576877
result2 3.1415926529660116
pi 3.141592653589793

Answer

Actually, your first loop would have int overflow in the calculation of (2 * i + 1) when i is large enough, so I wouldn't rely on the output of it.

The second loop, on the other hand, produces a more correct output, since (2 * j + 1) doesn't overflow, since it performs long multiplication.

This makes the "int - loop" calculates PI more accurate than "long - loop"

That's probably just a coincidence, since the calculations in the int loop overflow.

Comments