Why is there a different answer in the face and in the reverse?



  • Why when the sums are in the straight (value in variable) s1and reverse order (s2Is the answer different?

    #include <stdlib.h>
    #include <stdio.h>
    

    int main() {
    float s1, s2;
    long long int n;

    s1 = 0.; 
    for (n = 1; n &lt;= 100000000; n++) s1 += 1. / (n * n);
    s2 = 0.; 
    for (n = 100000000; n &gt;= 1; n--) s2 += 1. / (n * n);
    
    printf("%.17lf\n", s1); 
    printf("%.17lf\n\n", s2);
    system("pause"); 
    return 0;
    

    }



  • situation next (all as @avp) float is limited to the precision of a certain ring in the sign after the comma, so

    1 + 10000000000000000000 = 10000000000000000000 (1e19)
    

    Location of float in area 7 after comma, so the same number 10000000000000000000 float includes only the first 7 digits 1000000*************and the rest do not affect any number, that is.

    999999999999 + 10000000000000000000 = 10000000000000000000 (1e19)
    

    Now what do you two cycles of yours:

    The first cycle starts to fold from a larger number to a smaller one, at some point it doesn't matter what you're shaking, it won't affect the result.

    for float in your code after n = 4096 All other deductions are so small as to the amount that does not affect the amount

    The second cycle begins to fold from smaller numbers to large, so the non-recognized in the first case, after n = 4096, all adds a value that affects the total

    so, you see the difference.

        s1  1.64472532  float
        s2  1.64493406  float
    

    In the first case, smaller in the second largest in the amount n = 4096 before n = 100000000♪ And actually somewhere ♪ n = 370728

    By the way, double Mantissus is much larger (the whole type is 8 bytes instead of 4 for float), so the results will be different for the reasons described above, but they will be smaller.

        s1  1.6449340578345750  double
        s2  1.6449340568482265  double
    

    and in the first cycle the rechargings shall not be counted except c n = 94906266



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2