0

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);

    }

1 Answers1

1
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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • That's quite interesting. Thanks, though I'm not sure changing to fabs has yielded the correct answer. – user3525783 May 21 '14 at 04:59
  • @user3525783: What answer did you get before the modification? What answer do you get now and what answer do you think is correct? Note that rounding errors may play a role as well. – Martin R May 21 '14 at 05:02
  • Well, it just keeps printing up to 300,000 and kept going. I'm pretty sure it's not supposed to go that long. – user3525783 May 21 '14 at 05:04
  • @user3525783: In my test is stops at 577490. Note that you can improve the performance by 1) Calculating `pow(10,-6)` in advance and 2) Removing the `NSLog()` inside the loop. – Martin R May 21 '14 at 05:06
  • Hmm, mine has kept going past 600,000. I will rerun it with fabs(sqrt(6*s) - 3.141592). Before I did it with fabs(sqrt(6*s) - 3.141593) – user3525783 May 21 '14 at 05:10
  • Actually you should check the value of `fabs(sqrt(6*s) - M_PI)`. In that cast it stops at 954931. – Martin R May 21 '14 at 05:16
  • It kept going past 600,000 again. Here is the latest code: http://pastie.org/9194846 – user3525783 May 21 '14 at 05:18
  • Well, we shouldn't need m_pi here. We know what pi is to 6 decimal places. It is 3.141592 (or also could use 3.141593) – user3525783 May 21 '14 at 05:19
  • You got your output in .02 seconds? That's unbelievable. Mine is taking like a minute (I don't have a clock set, but definitely not under a second) – user3525783 May 21 '14 at 05:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/54081/discussion-between-martin-r-and-user3525783). – Martin R May 21 '14 at 05:24