Both the Math library and the Python library in Python have functions for finding logarithms.
import numpy as np
import math
1. Numpy library
1.1 Find the logarithm to base e, 2, 10
Function | function |
---|---|
np.log(x) | Logarithm based on e (natural logarithm) |
np.log10(x) | Log base 10 |
np.log2(x) | Logarithm to base 2 |
np.log1p(x) | Equivalent to: np.log(x + 1) |
Note: np.expm1(x) is equivalent to np.exp(x) – 1, which is also the inverse operation of np.log1p(x).
1.2 Find the base logarithm of any number
In Numpy, the logarithm based on any number needs to use the base exchange formula:
For example: base 3, logarithm of 5
The code is written as:
np.log(5)/np.log(3)
2. Math library
2.1 Find the logarithm to base e, 2, 10
Exactly the same as the usage in Numpy
Function | function |
---|---|
math.log(x) | Logarithm based on e (natural logarithm) |
math.log10(x) | Logarithm to base 10 |
math.log2(x) | base 2 logarithm |
math.log1p(x) | Equivalent to: math.log(x + 1), used for data smoothing |
Note: math.expm1(x) is equivalent to math.exp(x) – 1, which is also the inverse operation of math.log1p(x).
2.2 Find the base logarithm of any number
math.log(x, n)
Where n is the base
3. the difference
Why is there a method to find the logarithm in the Math library, but the same function is built in the Numpy library?
the reason:
In the math library, the input x of the function can only be a single number.
math.log10(100)[out]:2.0
If the input is a list:
math.log10([10,100]) #Will report an error
TypeError: must be real number, not list
In the Numpy library, the input x of the function can be not only a single number, but also a list or a Numpy array.
np.log10([10,100])[out]:array([1.,2.])
np.log10([[10,100],[1000,10000]])[out]:array([[1.,2.],[3.,4.]])
The result is a Numpy array. That is to say, the functions in Numpy can realize batch processing of each element without looping.
So far this article on the summary of the logarithm method in Python is introduced. For more related Python logarithm content, please search for ZaLou.Cn's previous articles or continue to browse the related articles below. I hope you will support ZaLou more in the future. Cn!
Recommended Posts