Python provides several built-in logarithmic functions through the math module for calculating logarithms with different bases and applications. Lets see a example:
import math
# Printing the log base e of 14
print ("Natural logarithm of 14 is : ", end="")
print (math.log(14))
# Printing the log base 5 of 14
print ("Logarithm base 5 of 14 is : ", end="")
print (math.log(14,5))
Output
Natural logarithm of 14 is : 2.6390573296152584 Logarithm base 5 of 14 is : 1.6397385131955606
log(a,(Base)) function returns the natural logarithm (base e) of a. If a second argument is provided, it returns the logarithm of a with respect to the specified base.
Syntax:
math.log(a,Base)
Parameters:
- a: The numeric value
- Base: Base to which the logarithm has to be computed.
Return Value: Returns natural log if 1 argument is passed and log with specified base if 2 arguments are passed.
Exceptions: Raises ValueError if a negative number is passed as argument.
log2(a)
import math
print ("Logarithm base 2 of 14 is : ", end="")
print (math.log2(14))
Output
Logarithm base 2 of 14 is : 3.807354922057604
This function is used to compute the logarithm base 2 of a. Displays more accurate result than log(a,2).
Syntax:
math.log2(a)
Parameters:
- a: The numeric value
Return Value: Returns logarithm base 2 of a
Exceptions: Raises ValueError if a negative number is passed as argument.
log10(a)
import math
print ("Logarithm base 10 of 14 is : ", end="")
print (math.log10(14))
Output
Logarithm base 10 of 14 is : 1.146128035678238
This function is used to compute the logarithm base 10 of a. Displays more accurate result than log(a,10). One of its application is that it is used to compute the number of digits of a number.
Syntax:
math.log10(a)
Parameters:
- a: The numeric value
Return Value: Returns logarithm base 10 of a
Exceptions: Raises ValueError if a negative number is passed as argument.
log1p(a)
import math
print ("Logarithm(1+a) value of 14 is : ", end="")
print (math.log1p(14))
Output
Logarithm(1+a) value of 14 is : 2.70805020110221
math.log1p(a) computes log(1 + a) accurately, especially when a is very close to zero.
Syntax:
math.log1p(a)
Parameters:
- a: The numeric value
Return Value: Returns log(1+a)
Exceptions: Raises ValueError if the argument is less than or equal to -1.