Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Other Bases, and the Exact Answers (BigFloat)

log2, log10, log, exp2 and exp10 have something the natural exponential and logarithm do not: arguments whose answers a float holds exactly. log2(8) is three, and three is a float.

That matters because a correctly rounded transcendental function works by deciding its rounding rather than assuming it — evaluating wider than asked until every value the error allows rounds the same way. An answer sitting exactly on a representable value can never be decided that way, however wide the evaluation goes, because there are values on both sides of it that round differently. So those arguments are recognized first, from the integer significand, and answered exactly:

from decimo.bigfloat.exponential import exp2, log, log10, log2

print(log2(BigFloat.power_of_two(-70), 53))        # exactly -70
print(log10(BigFloat.from_int(1000), 53))          # exactly 3
print(log(BigFloat.from_int(27), BigFloat.from_int(3), 53))   # exactly 3
print(log(BigFloat.from_int(3), BigFloat.from_int(9), 53))    # exactly 0.5
print(exp2(BigFloat.from_int(10), 53))             # exactly 1024

Which arguments those are has an exact answer in each case, and each is worth knowing:

  • log2(x) is exact exactly when x is a power of two, which is every argument whose significand is a single bit, at any exponent.
  • log10(x) is exact exactly when x is 10^k for a k at nought or above. A negative power of ten is not a binary float at all — a fifth is not a dyadic rational — so log10 of the float nearest a thousandth is irrational and a hair away from -3, and it is answered by the series.
  • log(x, base) is exact whenever the answer is exactly representable, which includes log(3, 9) = 0.5 and not only the whole answers. An answer that is exact but not representable, like log(9, 27) = 2/3, goes through the series and comes back correctly rounded like any other.
  • exp2(x) is exact exactly when x is a whole number, and exp10(x) when x is a whole number at nought or above and 10^x still fits the precision asked for. Past that 10^x is not representable, so the series settles on it.
  • expm1 and log1p are exact only at zero, where both are zero with the sign of the argument, and expm1(-Infinity) which is exactly minus one.