expm1()
Today, we will discuss the expm1() function in PHP. This function is used to calculate the exponential value of a number minus 1.
The PHP expm1() function returns e raised to the power of a number, minus 1 — that is, exp(x) - 1. Its value is in computing this result accurately for small x, where the naive exp($x) - 1 loses precision. This page explains what expm1() does, its syntax, when to reach for it instead of exp(), and the gotcha it exists to solve.
Syntax
expm1(float $num): float| Parameter | Description |
|---|---|
$num | Required. The exponent. Any number — positive, negative, or zero. Non-float values are coerced to float. |
Return value: e raised to the power of $num, minus 1, as a float. Here e is Euler's number (≈ 2.718281828).
Basic example
Because e^2 ≈ 7.389056, subtracting 1 gives the output:
6.3890560989307(PHP prints 14 significant digits by default, controlled by the precision INI setting.)
Why not just write exp($x) - 1?
For most inputs, expm1($x) and exp($x) - 1 give the same answer. The difference appears when $x is very close to zero.
When $x is tiny, exp($x) is very close to 1, so exp($x) - 1 subtracts two nearly-equal floating-point numbers. Most of the significant digits cancel out — a problem known as catastrophic cancellation — and the result is much less precise. expm1() is implemented to compute e^x - 1 directly, keeping full precision:
<?php
$x = 1e-15;
echo exp($x) - 1; // imprecise: digits cancel
echo "\n";
echo expm1($x); // accurate
?>The naive subtraction returns roughly 1.1102230246252E-15, while expm1() returns 1.0E-15, which is the correct value. Whenever you compound interest, decay, or growth over very small time steps, expm1() is the safe choice.
Negative and zero arguments
expm1() accepts the full range of real numbers:
<?php
echo expm1(0); // e^0 - 1 = 0
echo "\n";
echo expm1(-1); // 1/e - 1, a negative result
?>This outputs:
0
-0.63212055882856Note that expm1(0) is exactly 0, and negative arguments produce results between -1 and 0.
When to use expm1()
- Financial math where rates are small (e.g. converting an annual rate to a per-second rate).
- Continuous growth or decay models evaluated over tiny intervals.
- Any formula of the form
e^x - 1wherexmay approach zero.
For the inverse direction — computing log(1 + x) accurately for small x — use the companion function log1p(). For ordinary exponentiation without the -1, use exp().
Conclusion
expm1() computes e^x - 1 with full floating-point precision, even when x is near zero where exp($x) - 1 would lose accuracy. Reach for it in scientific and financial calculations involving small exponents; for everything else, exp() is fine. See also its inverse, log1p().