The math.log
function returns the logarithm of a number in the specified base. If no base is provided, it returns the natural logarithm (base e) of the number.
Syntax
math.log(x [, base])
Parameters
- x: A number greater than 0.
- base (optional): The base of the logarithm. If not specified, the base is e.
Return value
The logarithm of x
in the specified base. If x
is ≤ 0, the function returns NaN
.
Description
math.log
computes the logarithm of x
. By default, it uses the natural logarithm (base e). To compute the logarithm in a different base, provide the base as the second argument. The relationship for logarithms can be expressed as:
Examples
Using math.log()
print(math.log(-1)) -- NaN
print(math.log(0)) -- NaN
print(math.log(1)) -- 0
print(math.log(10)) -- 2.302585092994046
print(math.log(math.huge)) -- Infinity
Using math.log()
with a different base
To calculate the logarithm of y
with base x
:
function getBaseLog(x, y)
return math.log(y) / math.log(x)
end
print(getBaseLog(10, 1000)) -- 2.9999999999999996 (approx. 3)
See also
math.exp()
math.log1p(x)
math.log10(x)
math.log2(x)
math.pow(base, exp)