Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Math Functions

PHP pi() and M_PI

Reference for PHP pi(), M_PI and the other math constants such as M_E, M_SQRT2 and PHP_FLOAT_EPSILON, with precision notes and circle examples.

pi() returns the value of ฯ€ as a float, exactly like the constant M_PI: 3.1415926535898 when printed with the default precision. The two are interchangeable, but the constant avoids a function call.

PHP defines a family of M_ constants for common mathematical values, plus constants that describe the limits of floats. All of them are ordinary float values, so they carry the usual double-precision accuracy of about 15 to 17 significant digits.

PHP
<?php
echo M_PI;                      // 3.1415926535898
var_dump(pi() === M_PI);        // bool(true)

Try it

PHP Circles with M_PI

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP The other constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
pi(): float
M_PI

pi() takes no parameters.

Constant Value
M_PI ฯ€, 3.14159265358979323846
M_PI_2, M_PI_4 ฯ€/2 and ฯ€/4
M_1_PI, M_2_PI, M_2_SQRTPI 1/ฯ€, 2/ฯ€ and 2/โˆšฯ€
M_E e, the base of natural logarithms
M_LOG2E, M_LOG10E, M_LN2, M_LN10 log2(e), log10(e), ln 2 and ln 10
M_SQRT2, M_SQRT1_2, M_SQRT3, M_SQRTPI โˆš2, 1/โˆš2, โˆš3 and โˆšฯ€
M_EULER The Euler-Mascheroni constant
M_LNPI ln(ฯ€)
PHP_FLOAT_EPSILON Smallest difference between 1.0 and the next float
PHP_FLOAT_MAX, PHP_FLOAT_MIN, PHP_FLOAT_DIG Largest float, smallest positive normal float, digits that survive a round trip

Return value: pi() returns a float.

Usage notes

  • pi() equals M_PI. There is no accuracy difference; use whichever reads better. Constants also work in const expressions and as defaults.
  • Display precision is controlled by the precision ini setting (14 by default for echo). var_dump() and json_encode() use serialize_precision, which shows the shortest string that round-trips.
  • Compare floats with a tolerance, for example abs($a - $b) < PHP_FLOAT_EPSILON, never with == after calculations.
  • Radians: angles in trigonometric functions are measured in radians, so M_PI is half a turn.
  • Huge accuracy needs: floats stop at about 16 digits. For more, use BCMath with a digit string.