在函数中使用if命令时的ValueError [英] ValueError when using if commands in function
问题描述
我正在创建一些函数,我可以调用use关键字来调用特定的函数,
I'm creating some functions that I can call use keywords to call out specific functions,
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")
尝试打印此数组时,会返回此信息,
When trying to print this array, this is returned,
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具有多个元素的数组的真值是不明确的。使用a.any()或a.all()
这里有什么问题?
推荐答案
在需要标量值的上下文中使用数组时会产生这种错误。它在 if
表达式中测试 a!= -Inf
。 a
和 b
这里是集成的边界点。它们应该是标量,而不是数组。但是你打电话给 quad
:
This kind of error results when you use an array in a context that expects a scalar value. It is testing a != -Inf
in an if
expression. a
and b
here are the boundary points of the integration. They should be scalars, not arrays. But you are calling quad
with:
quad(integrand, a, a)
a
这里是 a = 1 ./(1. + z)
, z
是 linspace <生成的数组/ code>。
a
here is a = 1./(1.+z)
, and z
is the array produced by linspace
.
integrand
也看起来有问题。它是从 a
派生的数组。相反,它应该是一个功能。带标量并返回值的东西。 HubbleParam
可能有效,或 lambda
或使用它的函数def。
integrand
also looks problematic. It is array derived from a
. It should, instead, be a function. Something that takes a scalar and returns a value. HubbleParam
might work, or a lambda
or function def using it.
这篇关于在函数中使用if命令时的ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!