从numpy的对数文档,我找到了以e、2和10为底的对数函数:
import numpy as np
np.log(np.e**3) #3.0
np.log2(2**3) #3.0
np.log10(10**3) #3.0
但是,如何在 numpy 中取以 n(例如 42)为底的对数?
如果你有 numpy 1.23 或更高版本,你可以使用 np.emath.logn:
import numpy as np
array = np.array([74088, 3111696]) # = [42^3, 42^4]
base = 42
exponent = np.emath.logn(base, array) # = [3, 4]
如果您的 numpy 版本较旧:
math.log
获得自定义底数的对数:
import math
number = 74088 # = 42^3
base = 42
exponent = math.log(number, base) # = 3
numpy.log
获得自定义底数的对数:
import numpy as np
array = np.array([74088, 3111696]) # = [42^3, 42^4]
base = 42
exponent = np.log(array) / np.log(base) # = [3, 4]
其中使用对数换底规则:
Numpy 的以 n 为底的对数函数是 np.emath.logn.
import numpy as np
arr = np.array([74088, 3111696]) # = [42^3, 42^4]
base = 42
np.emath.logn(base, arr) # array([3., 4.])
np.emath.logn(14, 14**3) # 3.0
请注意,与
math.log
不同,base 是第一个参数。此外,与math.log
不同,它可以处理负数(返回复数)。