在 python 中定义 lambda 函数时出现 ValueError

ValueError when defining a lambda function in python

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

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 是三个数组的元素最小值。最后一行给出了异常:

ValueError: setting an array element with a sequence.

有人可以解释错误并提出执行此集成的替代方法吗?

最后一行没有给出异常,因为它很好。当您尝试将 Vl 与整数或浮点数而不是数组一起使用时,您将遇到异常。以下代码按预期运行

x = np.random.randn(K.shape)
res = Vl(x)

用你的代码。如果您想将两个数组与一个数字进行比较,只需创建一个仅以该数字作为条目的数组,即

five_array = 5*np.ones(K.shape)
res = Vl(five_array)

对编辑的回答: 这是一个非常奇怪的集成,但如果这是你想要的,我会使用集成的定义来实现,即

x_int = np.linspace(0,pbar,len(K))
integral = Vl(x_int).mean()*pbar

你有一堆 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,)
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 调用 Vl 时使用标量,积分变量范围从 0 到 pbar。集成的本质是在一堆点上评估 Vl,然后适当地求和这些值。

Vl(0) 产生这个错误是因为它是

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

因此您需要更改 Vl 以使用标量 p,或直接对数组求和。

写作

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

可能已经让您了解其中的区别。 Vl 不适用于不同于全局 pxKR 是全局变量,x 是 lambda 局部变量。