Natural number logarithms #
This file defines two ℕ-valued analogs of the logarithm of n with base b:
log b n: Lower logarithm, or floor log. Greatestksuch thatb^k ≤ n.clog b n: Upper logarithm, or ceil log. Leastksuch thatn ≤ b^k.
These are interesting because, for 1 < b, Nat.log b and Nat.clog b are respectively right and
left adjoints of Nat.pow b. See pow_le_iff_le_log and le_pow_iff_clog_le.
Floor logarithm #
pow b and log b (almost) form a Galois connection. See also Nat.pow_le_of_le_log and
Nat.le_log_of_pow_le for individual implications under weaker assumptions.
Ceil logarithm #
clog b n, is the upper logarithm of natural number n in base b. It returns the smallest
k : ℕ such that n ≤ b^k, so if b^k = n, it returns exactly k.
Instances For
Computating the logarithm efficiently #
An alternate definition for Nat.log which computes more efficiently. For mathematical purposes,
use Nat.log instead, and see Nat.log_eq_logC.
Note a tail-recursive version of Nat.log is also possible:
def logTR (b n : ℕ) : ℕ :=
let rec go : ℕ → ℕ → ℕ | n, acc => if h : b ≤ n ∧ 1 < b then go (n / b) (acc + 1) else acc
decreasing_by
have : n / b < n := Nat.div_lt_self (by omega) h.2
decreasing_trivial
go n 0
but performs worse for large numbers than Nat.logC:
#eval Nat.logTR 2 (2 ^ 1000000)
#eval Nat.logC 2 (2 ^ 1000000)
The definition Nat.logC is not tail-recursive, however, but the stack limit will only be reached
if the output size is around 2^10000, meaning the input will be around 2^(2^10000), which will
take far too long to compute in the first place.
Adapted from https://downloads.haskell.org/~ghc/9.0.1/docs/html/libraries/ghc-bignum-1.0/GHC-Num-BigNat.html#v:bigNatLogBase-35-
Instances For
An auxiliary definition for Nat.logC, where the base of the logarithm is squared in each
loop. This allows significantly faster computation of the logarithm: it takes logarithmic time
in the size of the output, rather than linear time.