2016-11-13 78 views
-1
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函数,但我不断收到读取错误:NumPy的LOG10函数:AttributeError的: '浮动' 对象有没有属性 '日志10'

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

我试图将我的参数放入一个列表(s变量),但我得到了同样的错误信息。 FWHM和lumi都是带小数点的数字(我认为它们被称为浮点数)。

+3

什么是'bhm'?为什么要标记和导入星座?它不在任何地方使用。什么_exactly_是您的输入(使其成为原稿)?如果我忽略'bhm.L_1450'调用,只使用'lumi',那么整数,浮点数和数组都可以正常工作。你使用的是什么numpy版本? – MSeifert

回答

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]) 
+1

我认为这个问题与'(10 **(44))'产生的一个整数太大而无法用numpy的整数dtypes表示。 'np.array(10 ** 44)'是一个'np.object'数组,包含一个本地Python整数。 'np.iinfo(np.int64).max == 9223372036854775807',这只有10个左右。如果指数是在浮点数而不是ints上执行的,那么你会得到一个'np.float64'数组--np.array(10.0 ** 44.0).dtype == np.float64'。同样,如果指数是负数,那么你当然会得到一个浮点结果。 –

相关问题