IsLearning
IsLearning

Reputation: 91

How to calculate sum of Pi

I posted not long ago on how to compute the sum of Pi with openmp. But it seems something's off with my code. Because manually I get the right result, but when I program it, it gives wrong results, if someone can help me?

PS : s= 1/N

Sum of pi

#include <chrono>
#include <iostream>

double f(double x)
{
  return (4 / (1 + (x * x)));
}

int main()
{
    int i;
    const int N = 60;
    double s1=0.0; double s2=0.0; double s3=0.0;
    double pi = 0.0; double s4=0.0; double s5=0.0;
    
    for (int i=0; i<N; i++)
        {
            //pi+=((f(i/N)+f((i+1)/N))/2*N);
            s1 = f(i/N);
            s2 = f((i+1)/N);
            s3 = 2 * N;
            s4 = s1 + s2;
            s5 = s4 / s3;
            pi+=s5;
        }
        
  printf("Pi = %f",pi);
  return 0; 
}

Upvotes: 0

Views: 106

Answers (2)

Monogeon
Monogeon

Reputation: 394

  1. The reason the value is different is because variable 'i' as well as 'N' are int's. When dividing int by int the answer will always be int.

Easiest and fastest fix is to change one of the variables to a double eg.:

#include <chrono>
#include <iostream>

double f(double x)
{
  return (4 / (1 + (x * x)));
}

int main()
{
    const int N = 60;
    double s1=0.0; double s2=0.0; double s3=0.0;
    double pi = 0.0; double s4=0.0; double s5=0.0;

    for (double i=0; i<N; i++) // i changed the int to double for the 'i' declaration
        {
            //pi+=((f(i/N)+f((i+1)/N))/2*N);
            s1 = f(i/N);
            s2 = f((i+1)/N);
            s3 = 2 * N;
            s4 = s1 + s2;
            s5 = s4 / s3;
            pi+=s5;
        }

  //printf("Pi = %f",pi);
  std::cout << "Pi = " << pi << std::endl;
  return 0;
}
  1. Also since you're programming in c++ make sure to pick the better c++ alternative to some of the code:

printf is C. It still works but c++'s cout is a better alternative that's improved and safer in most cases.

  1. You also have an extra unneeded variable declaration. You're creating two 'i' variables. Once at the start and once in the loop.

Upvotes: 2

IsLearning
IsLearning

Reputation: 91

As I got it from the answers, the problem was in (i/N). Since the i int declared as an int we need to add ((double)i/N).

pi+=((f((double)i/N)+f(((double)i+1)/N))/(2*N));

Upvotes: 0

Related Questions