Monday, August 17, 2009

C++ Constant for PI

Where's the definition for pi? Doesn't C++ provide a constant? What about C?

The C++ standard doesn't provide a value for pi but it's simple to define yourself:

#include <iostream>
#include <cmath> // M_PI is not standard

using namespace std;

class MathConst {
public:
static const long double PI;
};

const long double MathConst::PI = acos((long double) -1);

int main() {
cout.precision(100);
cout << "PI ~ " << MathConst::PI << endl;
}
Output:

$ g++ MathConst.cpp -o pi
$ ./pi
PI ~ 3.14159265358979323851280895940618620443274267017841339111328125
That is accurate to 18 decimal places.

Here's a definition in C:

#include <math.h>
#include <stdio.h>

double pi() {
const double pi = acos((double) - 1);
return pi;
}

int main() {
printf("%.20f\n", pi());
return 0;
}

2 comments:

Anonymous said...

C++ doesn't. But C does.

#include <cstdio>

M_PI

mla said...

My understanding is that M_PI is not part of ANSI C.

I just tried it with cstdio and g++ and M_PI isn't declared.