PHP Reference ยท Math Functions
PHP trigonometric functions
Reference for PHP trigonometry: sin, cos, tan, asin, acos, atan, atan2, hyperbolic functions, deg2rad and rad2deg, with radians and NAN edge cases.
PHP provides the usual trigonometric functions: sin(), cos() and tan(), their inverses asin(), acos(), atan() and atan2(), and the hyperbolic variants sinh(), cosh(), tanh(), asinh(), acosh() and atanh().
All angles are in radians, not degrees. A full circle is 2ฯ radians (about 6.283). Convert with deg2rad() and rad2deg(). Results are floats, so sin(M_PI) is a tiny number close to zero rather than exactly zero.
<?php echo sin(M_PI / 2); // 1 echo round(cos(M_PI), 5); // -1 echo rad2deg(M_PI); // 180
Try it
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.
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
sin(float $num): float cos(float $num): float tan(float $num): float asin(float $num): float acos(float $num): float atan(float $num): float atan2(float $y, float $x): float deg2rad(float $num): float rad2deg(float $num): float
| Name | Description |
|---|---|
$num |
An angle in radians for sin, cos and tan. A ratio for asin and acos (must be between -1 and 1) and atan. |
$y, $x |
The coordinates for atan2(). Note that y comes first. |
Return value: a float. asin() and acos() return NAN outside the range -1 to 1.
Usage notes
- Radians, always. The most common bug is passing degrees. Wrap them in
deg2rad(). atan2($y, $x)gives an angle in the correct quadrant, from -ฯ to ฯ. Prefer it toatan($y / $x), which loses the signs and fails when$xis zero.- Rounding noise. Results such as
sin(M_PI)(about 1.2e-16) are not exactly zero. Round for display or compare with a small tolerance. tan()near 90 degrees returns a very large number, notINF, because ฯ/2 is not exactly representable.- Inverse hyperbolic functions have limited domains:
acosh()needs a value of at least 1,atanh()needs a value between -1 and 1. - Constants:
M_PI,M_PI_2andM_PI_4are handy for common angles.
Related
pi()andM_PI,pow()andsqrt(),round(),is_nan()- Lessons: Math functions, Numbers