Recipe 2.8. Calculating Exponents


2.8.1. Problem

You want to raise a number to a power.

2.8.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.8.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 exp( ) and pow( ), PHP returns INF (infinity) if the result is too large and NAN (not a number) on an error.

2.8.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.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net