I wrote a program to calculate the PI number with 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
No, a variable name can't be changed. Try another method like a 2-dimensional array to create another "variable" as you're iterating.
No. you might be able to use it's value, if you copy it to a variable that is declared outside of the loop, but then you could just as easily declare the variable itself out of the loop.
In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With