math.log(x)
gives the natural (base e
) logarithm of x
.
math.log(math.e) # 1.0
math.log(1) # 0.0
math.log(100) # 4.605170185988092
math.log
can lose precision with numbers close to 1, due to the limitations of floating-point numbers. In order to accurately calculate logs close to 1, use math.log1p
, which evaluates the natural logarithm of 1 plus the argument:
math.log(1 + 1e-20) # 0.0
math.log1p(1e-20) # 1e-20
math.log10
can be used for logs base 10:
math.log10(10) # 1.0
When used with two arguments, math.log(x, base)
gives the logarithm of x
in the given base
(i.e. log(x) / log(base)
.
math.log(100, 10) # 2.0
math.log(27, 3) # 3.0
math.log(1, 10) # 0.0