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

时间:2016-11-13 17:37:23

标签: python numpy astropy

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

2 个答案:

答案 0 :(得分:6)

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

假设64位整数,最大可表示整数为9,223,372,036,854,775,807(参见例如Wikipedia),大致为10**19。但是一旦超过这个值,Python就会回退到无限的整数表示(就像在你的情况下10**44)。但NumPy并不支持这种无限制的精确类型,因此结果将回落到object并且这些object数组支持所有(任何?) 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])

答案 1 :(得分:0)

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

any_np_array = []
any_np_array = any_np_array.astype(float)