Reputation: 91
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
#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
Reputation: 394
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;
}
printf
is C. It still works but c++'s cout
is a better alternative that's improved and safer in most cases.
Upvotes: 2
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