Skip to main content
 首页 » 编程设计

python之Numpy log10 函数 : AttributeError: 'float' object has no attribute 'log10'

2025年05月04日13lonelyxmas

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

请您参考如下方法:

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

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

解决方案很简单:将这个大数转换为 float :

>>> # 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])