PHP Numbers Calculating Exponents - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Numbers Calculating Exponents - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

## Thursday, May 9, 2019 ## PHP Numbers

### Calculating Exponents

#### Problem

You want to raise a number to a power.

#### Solution

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

// \$exp (e squared) is about 7.389
\$exp = exp(2);

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

// \$exp (2^e) is about 6.58
\$exp = pow( 2, M_E);
// \$pow1 (2^10) is 1024
\$pow1 = pow( 2, 10);
// \$pow2 (2^-2) is 0.25
\$pow2 = pow( 2, -2);
// \$pow3 (2^2.5) is about 5.656
\$pow3 = pow( 2, 2.5);
// \$pow4 ( (-2)^10 ) is 1024
\$pow4 = pow(-2, 10);
// is_nan(\$pow5) returns true, because
// fractional exponent of negative 2 is not a real number.
\$pow5 = pow(-2, -2.5);

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