0
{
    double piApprox = 0; /* Save the result in this variable */
    double epsilon = 0.0001;
    int i = 0; /* Write the amount of iterations needed in this variable */
    double lim = 0;

    /* Calculate here */
    while (pi - piApprox > epsilon) {
        i++;
        lim += 1. / (i * i);
        piApprox = sqrt(6*lim);
    }

    cout << "It takes " << i << " iterations to approximate Pi to: " << piApprox << endl;
    cout << "The difference is: " << pi - piApprox << " < " << epsilon << endl;
}

Okay so I have simple problem for my university course and I solved it but my teammates say that my conclusion is wrong.

So Question is what happens if we set epsilon to low for ex. 0.00000001. Okay its obvious that we will have an integer overflow problem with ii. But the real problem why the programm breaks happens somewhere else. It happens in the piApprox = sqrt(6lim). The i*i overflows and becomes negative number. Means lim will go eventually into negative numbers until it is so negative that it cannot be displayed anymore and turns into 0 which than causes piApprox squarerooting 0 which turns to infinity which causes our program to break.

Is this correct?

  • C++ does not define what happens when integer overflow occurs. If you are using a compiler that guarantees it will wrap modulo the appropriate value, and `i * i` may be negative. However, what do you think the sum of `1. / (i * i)` will be? Before `i * i` becomes negative, it will have accumulated many positive terms, and it will be some time before adding negative values can move the balance to a negative sum. That might not occur at all; the mathematics might work out such that `lim` never becomes negative. – Eric Postpischil Apr 12 '21 at 12:17
  • At some point, `i * i` would become zero in a wrapping implementation, and `1. / (i * i)` would evaluate to infinity in common C++ implementations, and then `lim` would be infinity, and `piApprox` would be too. If `lim` does become negative, then `sqrt(6*lim)` returns an implementation-defined value. Many implementations return a NaN. – Eric Postpischil Apr 12 '21 at 12:20
  • Overflow of signed integers is explicitly "undefined behavior" (cf https://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c) -- that means your code could crash, or just do something unexpected. – chtz Apr 12 '21 at 12:21
  • Testing in Apple Clang 11 shows the negative terms do not add up to enough to reduce `lim` below zero. When `i` reaches 65536, `i*i` becomes zero, and `lim` and `piApprox` become ∞. (Keep in mind this is behavior in a particular C++ implementation; it may vary in others.) – Eric Postpischil Apr 12 '21 at 16:25

0 Answers0