Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

2.11. Calculating Trigonometric Functions

Problem

You want to use trigonometric functions, such as sine, cosine, and tangent.

Solution

PHP supports many trigonometric functions natively: sin( ) , cos( ), and tan( ):

$cos = cos(2.1232);

You can also use their inverses: asin( ), acos( ), and atan( ):

$atan = atan(1.2);

Discussion

These functions assume their arguments are in radians, not degrees. (See Recipe 2.13 if this is a problem.)

The function atan2( ) takes two variables $x and $y, and computes atan($x/$y). However, it always returns the correct sign because it uses both parameters when finding the quadrant of the result.

For secant, cosecant, and cotangent, you should manually calculate the reciprocal values of sin( ), cos( ), and tan( ):

$n = .707;

$secant    = 1 / sin($n);
$cosecant  = 1 / cos($n);
$cotangent = 1 / tan($n);

Starting in PHP 4.1, you can also use hyperbolic functions: sinh( ), cosh( ), and tanh( ), plus, of course, asin( ), cosh( ), and atanh( ). The inverse functions, however, aren’t supported on Windows.

See Also

Recipe 2.13 for how to perform trig operations in degrees, not radians; documentation on sin( ) at http://www.php.net/sin, cos( ) at http://www.php.net/cos, tan( ) at http://www.php.net/tan, asin( ) at http://www.php.net/asin, acos( ) at http://www.php.net/acos, atan( ) at http://www.php.net/atan, and atan2( ) at http://www.php.net/atan2.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata