本文介绍了在python中定义lambda函数时出现ValueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用集成时,我会收到一个ValueError,但是我不明白为什么.这是我的简化代码:

I am receiving a ValueError when using integration, but I cannot understand why. Here is my simplified code:

import numpy as np
import scipy.integrate as integrate
pbar = 1
p = np.arange(0,pbar,pbar/1000)
h = lambda p: p**2/2+p*(1-p)
Kl = lambda p: h(p) +0.02
K = Kl(p)
R = 0.5*h(p) + 0.5*h(pbar)
Vl = lambda p: np.minimum.reduce([p, K, R])
integrate.quad(Vl, 0, pbar)[0]

Vl是三个数组的元素方式最小值.最后一行给出了例外:

Vl is the element-wise minimum of the three arrays. The last line gives the exception:

ValueError: setting an array element with a sequence.

有人可以解释该错误并提出另一种进行此集成的方法吗?

Can someone please explain the error and propose an alternative way of doing this integration?

推荐答案

您有一堆1000个元素数组:

You have a bunch of 1000 element arrays:

In [8]: p.shape
Out[8]: (1000,)
In [9]: K.shape
Out[9]: (1000,)
In [10]: R.shape
Out[10]: (1000,)
In [11]: np.minimum.reduce([p, K, R]).shape
Out[11]: (1000,)
In [12]: Vl(p).shape
Out[12]: (1000,)
In [8]: p.shape
Out[8]: (1000,)
In [9]: K.shape
Out[9]: (1000,)
In [10]: R.shape
Out[10]: (1000,)
In [11]: np.minimum.reduce([p, K, R]).shape
Out[11]: (1000,)
In [12]: Vl(p).shape
Out[12]: (1000,)

但是integrate.quad用标量(范围从0到pbar的整数变量rangine)调用Vl.积分的性质是在多个点上评估Vl,并适当地求和.

But integrate.quad is calling Vl with a scalar, an integration variable rangine from 0 to pbar. The nature of the integration is to evaluate Vl at a bunch of points, and sum the values appropriately.

Vl(0)会产生此错误,因为它是

Vl(0) produces this error because it is

In [15]: np.minimum.reduce([0, K, R])
ValueError: setting an array element with a sequence.

因此,您需要更改Vl以使用标量p,或直接在数组上执行求和.

So you need to change Vl to work with a scalar p, or perform your sum directly on the array.

写作

Vl = lambda x: np.minimum.reduce([x, K, R])

可能会让您陷入歧途. Vl不适用于与全局p不同的x. KR是全局变量,x是lambda的局部变量.

might have clued you into the difference. Vl does not work with x different from the global p. K and R are globals, x is local to the lambda.

这篇关于在python中定义lambda函数时出现ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-25 10:23