首页 > 解决方案 > 在 Python 中集成一个 lambda 列表函数

问题描述

在Python中我正在尝试

from scipy.integrate import quad
time_start = 0
fun = lambda time: [cos(time), sin(time)]
integral = lambda time: quad(fun, time_start, time)

并希望程序以integral列表的形式返回,其中元素是 的元素明智集成fun,所以[quad(cos, time_start, time), quad(sin, time_start, time)].

但是,我得到TypeError: must be real number, not list.

我该如何解决这个问题?

标签: pythonmathscipy

解决方案


不要quad在返回两个函数列表的函数上使用——相反,在两个函数上使用两次,然后将结果组合到一个列表中。scipy.integrate.quad 的文档给出了要集成的函数的可能签名,每个签名都表明该函数必须返回一个double值(float在 Python 中调用),而不是一个列表。

如果您无法更改 or 的定义time_startfun的参数或返回值integral,则可以使用此代码。

from math import cos, sin
from scipy.integrate import quad

# Global variables and constants used in function `integral`
time_start = 0
fun = lambda time: [cos(time), sin(time)]

# The desired function
def integral(time):
    """Return a list of two items containing the integrals of the two
    components of the `fun` function from `start_time` to `time`.
    """
    def fun0(time):
        return fun(time)[0]
    def fun1(time):
        return fun(time)[1]

    integral0 = quad(fun0, time_start, time)[0]
    integral1 = quad(fun1, time_start, time)[0]
    return [integral0, integral1]

那么语句的结果

print(integral(0), integral(pi/2), integral(pi))

[0.0, 0.0] [0.9999999999999999, 0.9999999999999999] [3.6775933888827275e-17, 2.0]

这就是你想要的,在精度误差范围内。


顺便说一句,使用lambda表达式创建函数然后将其分配给名称被认为是 Python 中的不良编程习惯。见这里,第五个要点。改用常规def块:

def fun(time):
    return [cos(time), sin(time)]

def integral(time):
    # as shown above

当然,使用time_startandfun作为全局变量,而不是作为 的参数integral,也是不好的做法,但我坚持你使用它们的方式。


推荐阅读