Numpy log10 function: AttributeError: 'float' object has no attribute 'log10'

Numpy log10 function: AttributeError: 'float' object has no attribute 'log10'

import numpy as np
import astropy as ap

def mass(FWHM, lumi):
    abs_lumi = bhm.L_1450(lumi)
    s1 = (FWHM/1000)
    s2 = ((abs_lumi)/(10**44))
    s = [(s1**2)*(s2**0.53)]
    #mass = np.log10((s1**2)*(s2**0.53)) + 6.66 #old way, didn't work
    mass = np.log10(s) + 6.66
    return mass

我正在尝试使用 numpy log10 函数,但我不断收到错误消息:

AttributeError: 'float' object has no attribute 'log10'

我尝试将我的参数放入一个列表(s 变量)中,但我收到了相同的错误消息。 FWHM 和 lumi 都是带小数点的数字(我觉得叫浮点数)

这个问题的答案有点棘手,需要一些知识 Python 如何处理整数以及 numpy 如何强制转换类型。感谢@ali_m 的评论!

假设 64 位整数,最大的可表示整数是 9,223,372,036,854,775,807(参见示例 Wikipedia),大致是 10**19。但是,一旦超过这个值,Python 就会回退到无限整数表示(就像你的情况 10**44)。但是 NumPy 本身并不支持这种无限精度类型,因此结果将回退到 objects 而这些 object 数组 支持所有(任何? ) ufunc,比如 np.log10.

解决方法很简单:将这个大数转换为浮点数:

>>> # Negative powers will result in floats: 44 -> -44, * instead of /
>>> np.array([10, 20]) * 10**-44
array([  1.00000000e-43,   2.00000000e-43])

>>> # you could also make the base a float: 10 -> 10.
>>> np.array([10, 20]) / 10.**44
array([  1.00000000e-43,   2.00000000e-43])

>>> # or make the exponent a float: 44 -> 44.
>>> np.array([10, 20]) / 10**44.
array([  1.00000000e-43,   2.00000000e-43])

>>> # manually cast the result to a float
>>> np.array([10, 20]) / float(10**44)
array([  1.00000000e-43,   2.00000000e-43])

>>> # not working, result is an object array which cannot be used for np.log10
>>> np.array([10, 20]) / (10**(44))
array([1e-43, 2e-43], dtype=object)
>>> #                       ^---------that's the problem!

您只需更改函数中的第三行:

import numpy as np

def mass(FWHM, lumi):
    s1 = FWHM / 1000
    s2 = lumi * 10**-44   # changed line, using the first option.
    s = s1**2 * s2**0.53
    mass = np.log10(s) + 6.66
    return mass

这至少适用于我所有的测试输入,例如:

>>> mass(np.array([10., 20]), np.array([10., 20]))
array([-20.13      , -19.36839411])

问题原因如上所述。一种简单的解决方案是使用 .astype().

转换数组类型
any_np_array = []
any_np_array = any_np_array.astype(float)