Search code examples
objective-ccintegralriemann

Riemann Sum Estimation


I'm trying to calculate the value of n that solves the problem below. I am not exactly sure where I am messing up. I tried using a do while loop also, but I am having trouble figuring out the logic error. Could anyone assist?

If S = √ (6*( 1+1/2^2+1/3^2 +1/4^2 + 1/5^2 + ... ) ) = (pi^2)/6, after how many terms will the sum be equal to PI to 6 decimal places. PI to 6 decimal places is 3.141592. The relevant part of my code is shown below:

    double s = 0;


    for(int n=1;abs(sqrt(6*s) - 3.141592) >= pow(10,-6);n++) {

        s += (1/(pow(n,2)));

            NSLog(@"%i",n);

    }

Solution

  • int abs(int i)
    

    computes the absolute value of an integer. Therefore in

    abs(sqrt(6*s) - 3.141592)
    

    the floating point number sqrt(6*s) - 3.141592 is converted to an int first, which gives zero as soon as the absolute value of this number is less than one.

    You want to use fabs() instead.