Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the PI constant in C++

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?

like image 224
Etan Avatar asked Nov 13 '09 08:11

Etan


People also ask

How do you declare a constant in C?

Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

What does M_PI mean in C++?

M_PI. Pi, the ratio of a circle's circumference to its diameter. M_PI_2.

What does M_PI mean?

M_PI is defined as a macro #define M_PI 3.14159265358979323846264338327950288. in math. h and part of the POSIX standard. The values are identical, but you should use M_PI for portability reasons. (And for Swift, see How to get mathemical PI constant in Swift)


2 Answers

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:

  1. on newer platforms (at least on my 64 bit Ubuntu 14.04) I do not need to define the _USE_MATH_DEFINES

  2. On (recent) Linux platforms there are long double values too provided as a GNU Extension:

    # define M_PIl          3.141592653589793238462643383279502884L /* pi */ 
like image 121
Ferenc Deak Avatar answered Sep 22 '22 01:09

Ferenc Deak


Pi can be calculated as atan(1)*4. You could calculate the value this way and cache it.

like image 43
Konamiman Avatar answered Sep 21 '22 01:09

Konamiman