PHP Reference ยท Math Functions
PHP exp() and log() functions
Reference for PHP exp(), expm1(), log(), log10() and log1p(): natural and custom-base logarithms, domain errors, INF and NAN results.
exp($x) returns e raised to the power $x, where e is about 2.71828. log($x) is its inverse: the natural logarithm. With a second argument, log($x, $base) computes a logarithm in any base. PHP also has a dedicated log10(), which is more accurate than dividing two natural logs. There is no log2(); use log($x, 2).
Logarithms are only defined for positive numbers. PHP does not throw for invalid input: log(0) is -INF and log(-1) is NAN.
<?php echo exp(1); // 2.718281828459 echo log(M_E); // 1 echo log(8, 2); // 3
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
exp(float $num): float expm1(float $num): float log(float $num, float $base = M_E): float log10(float $num): float log1p(float $num): float
| Name | Description |
|---|---|
$num |
The value. For the logarithm functions it must be greater than zero to give a finite result (log1p() needs more than -1). |
$base |
Optional base of log(). Defaults to e. Must be greater than zero, or a ValueError is thrown. |
Return value: a float. Special values are INF, -INF and NAN.
Errors: log() throws a ValueError when $base is zero or negative; a base of 1 returns NAN.
Usage notes
log()is the natural logarithm, unlike calculators where "log" often means base 10. Uselog10()for that.- Prefer
log10()overlog($x, 10)when you want exact results for powers of ten. For base 2 there is no dedicated function, solog($x, 2)is the way; it can be off in the last digit for large powers of two. expm1()andlog1p()computeexp($x) - 1andlog(1 + $x)accurately when$xis close to zero, where the plain forms lose digits to rounding.- Overflow and underflow:
exp()of a large number isINF; of a very negative number it is0. - Floating-point rounding:
log10(1000)is exactly3, but dividing logs (log(1000) / log(10)) may give2.9999999999999996. Round, or avoidfloor()on such quotients. - Powers with any base:
pow()is the inverse for non-natural bases.