Math constant PI value in C

Calculating PI value is one of the complex problem and wikipedia talks about the approximations done for it and says it's difficult to calculate PI accurately.

How does C calculate PI? Does it calculate it every time or is it using a less accurate fixed value?


In C Pi is defined in math.h: #define M_PI 3.14159265358979323846


The closest thing C does to "computing π" in a way that's directly visible to applications is acos(-1) or similar. This is almost always done with polynomial/rational approximations for the function being computed (either in C, or by the FPU microcode).

However, an interesting issue is that computing the trigonometric functions (sin, cos, and tan) requires reduction of their argument modulo 2π. Since 2π is not a diadic rational (and not even rational), it cannot be represented in any floating point type, and thus using any approximation of the value will result in catastrophic error accumulation for large arguments (e.g. if x is 1e12, and 2*M_PI differs from 2π by ε, then fmod(x,2*M_PI) differs from the correct value of 2π by up to 1e12*ε/π times the correct value of x mod 2π. That is to say, it's completely meaningless.

A correct implementation of C's standard math library simply has a gigantic very-high-precision representation of π hard coded in its source to deal with the issue of correct argument reduction (and uses some fancy tricks to make it not-quite-so-gigantic). This is how most/all C versions of the sin/cos/tan functions work. However, certain implementations (like glibc) are known to use assembly implementations on some cpus (like x86) and don't perform correct argument reduction, leading to completely nonsensical outputs. (Incidentally, the incorrect asm usually runs about the same speed as the correct C code for small arguments.)