Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

numeric

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 
like image 351
programer310 Avatar asked Jan 05 '16 11:01

programer310


People also ask

How do you change a variable in a for loop in Java?

No, a variable name can't be changed. Try another method like a 2-dimensional array to create another "variable" as you're iterating.

Can you use a variable from a for loop in Java?

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.

Can you have two variables in a for loop Java?

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.


2 Answers

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.

like image 121
Eran Avatar answered Sep 21 '22 17:09

Eran


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.

like image 38
Suresh Atta Avatar answered Sep 21 '22 17:09

Suresh Atta