How to use the PI constant in C++
How to use the PI constant in C++
Question
I want to use the PI constant and trigonometric functions in some C++ program. I get the trigonometric functions with include <math.h>
. However, there doesn't seem to be a definition for PI in this header file.
How can I get PI without defining it manually?
Accepted Answer
On some (especially older) platforms (see the comments below) you might need to
#define _USE_MATH_DEFINES
and then include the necessary header file:
#include <math.h>
and the value of pi can be accessed via:
M_PI
In my math.h
(2014) it is defined as:
# define M_PI 3.14159265358979323846 /* pi */
but check your math.h
for more. An extract from the "old" math.h
(in 2009):
/* Define _USE_MATH_DEFINES before including math.h to expose these macro
* definitions for common math constants. These are placed under an #ifdef
* since these commonly-defined names are not part of the C/C++ standards.
*/
However:
on newer platforms (at least on my 64 bit Ubuntu 14.04) I do not need to define the
_USE_MATH_DEFINES
On (recent) Linux platforms there are
long double
values too provided as a GNU Extension:# define M_PIl 3.141592653589793238462643383279502884L /* pi */
Read more… Read less…
Pi can be calculated as atan(1)*4
. You could calculate the value this way and cache it.
You could also use boost, which defines important math constants with maximum accuracy for the requested type (i.e. float vs double).
const double pi = boost::math::constants::pi<double>();
Check out the boost documentation for more examples.
Get it from the FPU unit on chip instead:
double get_PI()
{
double pi;
__asm
{
fldpi
fstp pi
}
return pi;
}
double PI = get_PI();
I would recommend just typing in pi to the precision you need. This would add no calculation time to your execution, and it would be portable without using any headers or #defines. Calculating acos or atan is always more expensive than using a precalculated value.
const double PI =3.141592653589793238463;
const float PI_F=3.14159265358979f;
Rather than writing
#define _USE_MATH_DEFINES
I would recommend using -D_USE_MATH_DEFINES
or /D_USE_MATH_DEFINES
depending on your compiler.
This way you are assured that even in the event of someone including the header before you do (and without the #define) you will still have the constants instead of an obscure compiler error that you will take ages to track down.