Infinite loop in program written as an exercise about finding the value of Pi

Viewed 101

I have this assignment

The value of Pi can be determined by the following product

         2 * 2   4 * 4   6 * 6               N * N
Pi = 2 * ----- * ----- * ----- * ... * -----------------
         1 * 3   3 * 5   5 * 7         (N - 1) * (N + 1)

Write a C program that calculates the approximated value of Pi as long as the general term is greater than 1 + 10-9.

To solve it, I wrote this code:

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

int main() {
  double pi;
  const double End =
      1.0 + (1.0 / (10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0));
  double N = 2.0;

  pi = 2.0 * ((N * N) / ((N - 1.0) * (N + 1.0)));

  while (pi > End) {

    N += 2.0;
    pi *= ((N * N) / ((N - 1.0) * (N + 1.0)));
  }
  printf("%lf", pi);

  return 0;
}

I can't really understand how things work. I managed to use only double variables and added .0 to all the number literals, but the program is stuck and doesn't give any value when I launch it.

Why?

2 Answers

A simple solution would be to keep track of the old value, and thus replace the loop to the following (needs <math.h>)

double pi_old = pi + 1e9; // initialize to large value
while (fabs(pi-pi_old) > End){
    pi_old = pi; // store this

    // then compute next
    N += 2.0;
    pi *= ((N * N) / ((N - 1.0) * (N + 1.0)));
}

Also, As I've commented,

const double End =
      1.0 + (1.0 / (10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0 * 10.0));

is equivalent to

const double End = 1.0 + ( 1.0e-9 );  // 1.0e-9 = 1.0*10^(-9)

This condition while (pi > End) does not match the requirements.
It will loop while the total product is larger than roughly 1, which for any approximiation of Pi will be an endless loop.
The decription refers to only the last part (N*N)/( (N-1) * (N+1) ) being larger than 1 + a little.

So the solution is to calculate that last part separately and use only it in the loop condition.

(I intentionally do not provide more details or code, because of
How do I ask and answer homework questions?
)

Related