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

You have integer overflow.

The max capacity of a signed int is (2^31)-1, or 2,147,483,647.

(1,607,702,095 * 2) is 3215404190, which is bigger than 2,147,483,647.

When you change i to a long you increase the capacity of i to (2^63)-1.


2 * i when i is close to the end of your loop will overflow the max value for an int which is 2147483647.

Using a long that operation doesn't overflow.

The correct procedure is using a long type. Probably because values are added and removed around the correct PI for some strange behavior the overflows momentarily compute to a value closer to the right PI.

I suppose that change the limit of the for loop of few values will change the final result to a value that is more far from the right PI.


Because you are getting overflow at the line

result1 += sign/(2 * i + 1);

Where the value of 2*i cross the max integer value

int range is -2,147,483,648 to 2,147,483,647 but when you do 2*i for greater value it crosses that range.

Better to be stick with long and that gives you correct output.


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.

Tags:

Java

Numeric