title: Java For-loop changes numeric result when changing type of loop variable
body: <p>I wrote a program to calculate the PI number with Leibniz formula:</p>
  
  <p>[<img src="https://i.stack.imgur.com/d962E.png" alt="Leibniz formula]"></p>
  
  <p>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.</p>
  
  <pre><code>public static void main(String[] args) {
      double result1 = 0;
      double result2 = 0;
      double sign = 1;
  
      for (int i = 0; i &lt;= 1607702095; i++) {
          result1 += sign/(2 * i + 1);
          sign *= -1;
      }
      sign = 1;
  
      for (long j = 0; j &lt;= 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);
  }
  </code></pre>
  
  <p>And the result is: </p>
  
  <pre><code>result1  3.141592653576877
  result2  3.1415926529660116
  pi       3.141592653589793
  </code></pre>