Sub topic 13
Powers, Roots, and Logarithms
This chapter assumes you already know the arithmetic operators from earlier chapters, including the basic ** operator, and that you understand why binary floating point rounds values like 0.1. All examples run unchanged in Node.js or a browser console.
Powers, roots, and logarithms look simple. Their edge cases are where bugs come from: a cube root that returns NaN, a logarithm that comes out as 2.9999999999999996, or a distance formula that overflows to Infinity. This chapter covers the working model for each function family and the errors that come up most often.
Powers: `**` and `Math.pow`
The ** operator and Math.pow(base, exponent) compute the same result for Number values. They differ in three ways.
| Aspect | `**` | `Math.pow` |
|---|---|---|
| Form | Operator, right-associative | Function |
| Works with BigInt | Yes (`2n ** 64n`) | No, throws `TypeError` |
| Usable as a callback | No | Yes (`[1, 2, 3].map(n => Math.pow(2, n))`, or pass it directly to `reduce`) |
| Unary minus on the base | Must use parentheses | No ambiguity |
console.log(2 ** 3 ** 2); // 512, evaluated as 2 ** (3 ** 2)
console.log((2 ** 3) ** 2); // 64
console.log((-2) ** 2); // 4
console.log(-(2 ** 2)); // -4
console.log(2 ** -1); // 0.5
console.log(2 ** 0.5); // 1.4142135623730951
console.log(2 ** 1024); // Infinity (overflow)
console.log(2 ** -1075); // 0 (underflow)
console.log(2n ** 64n); // 18446744073709551616n
try {
Math.pow(2n, 3n);
} catch (e) {
console.log(e instanceof TypeError); // true
}Writing -2 ** 2 without parentheses is a SyntaxError. The language refuses to guess whether you meant (-2) ** 2 or -(2 ** 2). Because the error comes from the parser, the whole script fails to load. You can't catch it with try.
Edge cases in exponentiation
Some results come from the IEEE 754 rules and the ECMAScript specification, and they can surprise you:
console.log(0 ** 0); // 1
console.log(NaN ** 0); // 1 (anything to the power 0 is 1)
console.log(1 ** Infinity); // NaN (C's pow returns 1 here; JavaScript does not)
console.log((-8) ** (1 / 3)); // NaN
console.log(Infinity ** -1); // 0
console.log((-0) ** -1); // -InfinityThe (-8) ** (1 / 3) case matters most in practice. 1 / 3 is not exactly one third. It is a binary fraction close to it. A negative number raised to a non-integer power has no real result, so the answer is NaN.
Roots
`Math.sqrt` and `Math.cbrt`
Math.sqrt returns the positive square root. For negative input it returns NaN. Math.cbrt returns the cube root, and it accepts negative input because every real number has a real cube root.
console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(-1)); // NaN
console.log(Math.sqrt(-0)); // -0
console.log(Math.cbrt(27)); // 3
console.log(Math.cbrt(-8)); // -2
console.log(Math.sqrt(2) ** 2); // 2.0000000000000004Squaring a square root does not always get the original value back. Each step rounds to the nearest double, so compare such results with a tolerance.
Nth roots with fractional exponents
No built-in function computes a general nth root. The usual approach is x ** (1 / n). That approach inherits the rounding in 1 / n:
console.log(64 ** (1 / 3)); // 3.9999999999999996
console.log(Math.cbrt(64)); // 4
function nthRoot(x, n) {
if (x < 0) {
if (n % 2 === 0) return NaN; // even root of a negative number
return -nthRoot(-x, n); // odd root: take the root of |x|, flip the sign
}
const guess = x ** (1 / n);
const rounded = Math.round(guess);
// Snap to an integer when that integer is an exact root
return rounded ** n === x ? rounded : guess;
}
console.log(nthRoot(64, 3)); // 4
console.log(nthRoot(-32, 5)); // -2
console.log(nthRoot(-16, 4)); // NaN
console.log(nthRoot(10, 2)); // 3.1622776601683795When a dedicated function exists, use it (Math.sqrt, Math.cbrt). It is correctly rounded or close to it, and it handles negative input properly.
`Math.hypot` and overflow
Math.hypot(a, b, ...) returns the square root of the sum of squares. It is the Euclidean length of a vector. Because it scales the values internally, it avoids the intermediate overflow that the naive formula hits:
const big = 1e200;
console.log(Math.sqrt(big ** 2 + big ** 2)); // Infinity (big ** 2 overflows)
console.log(Math.hypot(big, big)); // 1.4142135623730952e+200
console.log(Math.hypot(3, 4)); // 5
console.log(Math.hypot(1, 2, 2)); // 3
console.log(Math.hypot()); // 0
console.log(Math.hypot(3, NaN)); // NaN
console.log(Math.hypot(NaN, Infinity)); // InfinityThe last line shows a rule from the specification: if any argument is infinite, the result is Infinity, even when another argument is NaN.
Exponentials and Logarithms
| Function | Computes | Domain notes |
|---|---|---|
| `Math.exp(x)` | e to the power x | Overflows to `Infinity` above about 709.78 |
| `Math.expm1(x)` | e to the power x, minus 1 | Accurate for x near 0 |
| `Math.log(x)` | Natural log (base e) | `0` gives `-Infinity`; negative gives `NaN` |
| `Math.log10(x)` | Base-10 log | Same domain as `Math.log` |
| `Math.log2(x)` | Base-2 log | Same domain as `Math.log` |
| `Math.log1p(x)` | Natural log of 1 + x | Accurate for x near 0; `-1` gives `-Infinity` |
The related constants are Math.E, Math.LN2, Math.LN10, Math.LOG2E, and Math.LOG10E.
console.log(Math.exp(1)); // 2.718281828459045
console.log(Math.log(Math.E)); // 1
console.log(Math.log10(1000)); // 3
console.log(Math.log2(8)); // 3
console.log(Math.log(0)); // -Infinity
console.log(Math.log(-1)); // NaN
console.log(Math.exp(710)); // InfinityChange of base and its rounding error
To get a logarithm in an arbitrary base b, divide two logs: log_b(x) = ln(x) / ln(b). The division adds a second rounding step, and exact powers can come out just below the integer:
console.log(Math.log(1000) / Math.LN10); // 2.9999999999999996
console.log(Math.log10(1000)); // 3
console.log(Math.log(243) / Math.log(3)); // 4.999999999999999
function logBase(x, base) {
return Math.log(x) / Math.log(base);
}
console.log(Math.floor(logBase(243, 3))); // 4, but 3 ** 5 is 243Use Math.log10 and Math.log2 for those bases. For other bases, don't pass the result straight to Math.floor. Round it first and check the candidate:
function integerLog(x, base) {
let k = Math.round(Math.log(x) / Math.log(base));
if (base ** k > x) k -= 1; // the rounded guess overshot
else if (base ** (k + 1) <= x) k += 1; // the guess fell one short
return k;
}
console.log(integerLog(243, 3)); // 5
console.log(integerLog(242, 3)); // 4Precision near zero: `expm1` and `log1p`
When x is tiny, 1 + x loses most of x's digits before Math.log ever sees the value. The same loss happens in Math.exp(x) - 1. The log1p and expm1 functions compute these results directly:
const tiny = 1e-15;
console.log(Math.log(1 + tiny)); // 1.110223024625156e-15 (about 11% off)
console.log(Math.log1p(tiny)); // 9.999999999999995e-16
console.log(Math.exp(1e-10) - 1); // 1.000000082740371e-10
console.log(Math.expm1(1e-10)); // 1.00000000005e-10Financial code meets this case with small interest rates, for example continuous compounding computed as Math.expm1(rate * years).
Choosing the Right Function
Common Errors
- Writing
-x ** 2without parentheses. It is aSyntaxErrorthat stops the whole script. - Expecting
(-8) ** (1/3)to equal-2. It returnsNaN. UseMath.cbrt. - Calling
Math.flooron a change-of-base result. Exact powers can come out one below the correct answer. - Counting digits with
Math.floor(Math.log10(n)) + 1without guarding zero and negative numbers.Math.log10(0)is-Infinity, and negative input givesNaN. - Passing BigInt values to
Math.poworMath.sqrt. EveryMathfunction rejects BigInt with aTypeError.
Exercise
Write digitCount(n) that returns how many decimal digits the integer part of a Number has, so that digitCount(0) is 1, digitCount(-950) is 3, and digitCount(1000) is 4. Explain why a guard is needed if you use Math.log10.
Show answer
function digitCount(n) { const m = Math.abs(Math.trunc(n)); return m === 0 ? 1 : Math.floor(Math.log10(m)) + 1; } The guard is needed because Math.log10(0) is -Infinity, which would give -Infinity instead of 1, and Math.log10 of a negative number is NaN. That is why the function takes the absolute value first. Math.log10 returns exact results for powers of ten, so 1000 gives 4. For very large values, String(m).length switches to exponent notation above 1e21, so the log approach works over a wider range.
Exercise
Predict the output of each line: console.log(2 -2); console.log((-27) (1/3)); console.log(Math.cbrt(-27)); console.log(Math.hypot(Infinity, NaN)); console.log(Math.log1p(-1));
Show answer
0.25, then NaN (a negative base with a non-integer exponent), then -3, then Infinity (an infinite argument wins over NaN in hypot), then -Infinity (log1p(-1) is the natural log of 0).
Exercise
A colleague computes the number of bits needed for a positive integer n as Math.floor(Math.log(n) / Math.log(2)) + 1. Which function should replace the ratio, and why?
Show answer
Use Math.floor(Math.log2(n)) + 1. Dividing two natural logs rounds twice, so an exact power of two could come out slightly below the integer, and Math.floor would then undercount by one. Math.log2 returns exact results for powers of two.