Numpy log10函数:AttributeError:“float”对象没有属性“log10”

2024-09-21 07:45:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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都是带小数点的数字(我认为它们被称为浮点数)。


Tags: importnumpydefas错误npabsmass
2条回答

这个问题的答案有点棘手,需要了解Python如何处理整数以及numpy如何强制类型。多谢@ali嫒m的评论!

假设64位整数,最大的可表示整数是9,223,372,036,854,775,807(参见示例Wikipedia),大致是10**19。但是一旦超过这个值,Python就会返回到无限制整数表示(就像在您的例子中10**44)。但是这种无限精度的类型并没有得到NumPy的支持,所以结果将返回到objects,而这些object数组不支持所有(any?)ufuncs,比如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)

相关问题 更多 >

    热门问题