在函数中使用if命令时的ValueError

时间:2017-01-26 06:43:48

标签: python numpy if-statement scipy

我正在创建一些我可以调用使用关键字来调用特定函数的函数,

import scipy.integrate as integrate
import numpy as np

def HubbleParam(a, model = "None"):
    if model == "LCDM":
        Omega_L0 = 0.7
        Omega_m0 = 0.3 
        return np.sqrt( Omega_m0/a/a/a+ Omega_L0  )

    if model == "Q":
        Omega_Q0 = 0.7
        Omega_m0 = 0.3 
        return np.sqrt( Omega_m0/a/a/a + Omega_Q0/a )


def EmitterDistance(z, model = "None"):
    a = 1./(1.+z)
    if model == 'LCDM':
        integrand = 1./a/a/HubbleParam(a, model="LCDM")
        return [z , integrate.quad(integrand, a, 1.)[0] ]

    if model == "Q":
        integrand = 1/a/a/HubbleParam(a, model="Q")
        return [z, integrate.quad(inta, a, 1.)[0] ]

z = np.linspace(0.,5., 1000)

print EmitterDistance(z, model="LCDM")

尝试打印此数组时,会返回

Traceback (most recent call last):
  File      "/Users/alexandres/Desktop/Formation_Galaxies/Homework1/FoG_HW1.py", line 95, in <module>
    print EmitterDistance(z, model="LCDM")
  File "/Users/alexandres/Desktop/Formation_Galaxies/Homework1/FoG_HW1.py", line 87, in EmitterDistance
    return [z , integrate.quad(integrand, a, a)[0] ]
  File     "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/integrate/quadpack.py", line 315, in quad
points)
  File     "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/integrate/quadpack.py", line 364, in _quad
    if (b != Inf and a != -Inf):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
[Finished in 0.5s with exit code 1]
[shell_cmd: python -u     "/Users/alexandres/Desktop/Formation_Galaxies/Homework1/FoG_HW1.py"]
[dir: /Users/alexandres/Desktop/Formation_Galaxies/Homework1]
[path: /usr/bin:/bin:/usr/sbin:/sbin]

或更重要的是

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

这里有什么问题?

2 个答案:

答案 0 :(得分:0)

EmitterDistance()integrate.quad()的第一个参数应该是一个函数。但它是一个数组,而不是。

答案 1 :(得分:0)

在需要标量值的上下文中使用数组时会产生此类错误。它正在a != -Inf表达式中测试ifab这里是整合的边界点。它们应该是标量,而不是数组。但是你打电话给quad

 quad(integrand, a, a)

a此处为a = 1./(1.+z)zlinspace生成的数组。

integrand看起来也有问题。它是从a派生的数组。相反,它应该是一个功能。带标量并返回值的东西。 HubbleParam可能有效,或lambda或函数def使用它。