【问题标题】:ValueError when using if commands in function在函数中使用 if 命令时出现 ValueError
【发布时间】:2017-06-11 14:35:13
【问题描述】:

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

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()

这里有什么问题?

【问题讨论】:

    标签: python numpy if-statement scipy


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      当您在需要标量值的上下文中使用数组时,会出现这种错误。它正在if 表达式中测试a != -Infab 这里是积分的边界点。它们应该是标量,而不是数组。但是你打电话给quad

       quad(integrand, a, a)
      

      a这里是a = 1./(1.+z)zlinspace产生的数组。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-27
        • 2015-08-04
        • 1970-01-01
        • 2017-07-09
        • 2021-08-27
        • 2014-12-23
        • 2021-03-08
        • 2019-09-09
        相关资源
        最近更新 更多