且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

numpy的ValueError错误:与一个以上的元件的阵列的真值是不明确的。使用a.any()或a.all()leastsq

更新时间:2022-03-09 03:28:27

该错误信息可以复制这样的:

The error message can be reproduced like this:

import numpy as np
import scipy.integrate as integrate

xup = np.random.random(10)

def calka(x, OmM):
    return 1./math.sqrt(OmM*(1.+x)**3 + (1.-OmM))


# Passing a scalar value, 10, for the upper limit is fine:
integrate.quad(calka, 0., 10, args=(0.25,))
# (2.3520760256393554, 1.9064918795817483e-12)

# passing a vector, xup, raises a ValueError:
integrate.quad(calka, 0., xup, args=(0.25,))
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


现在,在code,以Z 是一个数组:

z=np.array([float(t[0]) for t in data0])

以Z 被传递给

leastsq(residuals,(0.25, 70), args=(z, mu, dmu))

XUP 被分配值以Z

def residuals(p, xup,y,dmu):
    return ((y-xlambda(p,xup))/dmu)**2

xlambda XUP - 向量 - 直接传递到

Inside xlambda, xup -- the vector -- is passed directly to quad:

def xlambda(p,xup): 
    H0=p
    calka1 = quad(calka, 0., xup, args=(p[0]))[0]

因此​​,ValueError错误。

Hence the ValueError.

presumably,你会想要 xlambda 来一次为 XUP 的每个值被调用。所以,你可以通过使用解决问题。

Presumably, you'd want xlambda to be called once for each value in xup. So you could fix the problem by using

def residuals(p, xup, y, dmu):
    xl = np.array([xlambda(p, x) for x in xup])
    return ((y-xl)/dmu)**2