2.8. Calculating Exponents

Problem

You want to raise a number to a power.

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)

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.

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.

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.