start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

2.9. Calculating Exponents

2.9.1. Problem

You want to raise a number to a power.

2.9.2. Solution

To raise e to a power, use exp( ):

$exp = exp(2);        // 7.3890560989307

To raise it to any power, use pow( ):

$exp = pow( 2, M_E);  // 6.5808859910179

$pow = pow( 2, 10);   // 1024
$pow = pow( 2, -2);   // 0.25
$pow = pow( 2, 2.5);  // 5.6568542494924

$pow = pow(-2, 10);   // 1024
$pow = pow( 2, -2);   // 0.25
$pow = pow(-2, -2.5); // NAN (Error: Not a Number)

2.9.3. Discussion

The built-in constant M_E is an approximation of the value of e. It equals 2.7182818284590452354. So exp($n) and pow(M_E, $n) are identical.

It's easy to create very large numbers using exp( ) and pow( ); if you outgrow PHP's maximum size (almost 1.8e308), see Recipe 2.14 for how to use the arbitrary precision functions. With these functions, PHP returns INF, infinity, if the result is too large and NAN, not-a-number, on an error.

2.9.4. See Also

Documentation on pow( ) at http://www.php.net/pow, exp( ) at http://www.php.net/exp, and information on predefined mathematical constants at http://www.php.net/math.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.