NumPy:以 n

问题描述 投票:0回答:2

numpy的对数文档,我找到了以e210为底的对数函数:

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)为底的对数?

python math numpy logarithm
2个回答
214
投票

如果你有 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]

其中使用对数换底规则:

\log_b(x)=\log_c(x)/\log_c(b)


1
投票

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
不同,它可以处理负数(返回复数)。

© www.soinside.com 2019 - 2024. All rights reserved.