python - 在 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
.
我该如何解决这个问题?
解决方案
不要quad
在返回两个函数列表的函数上使用——相反,在两个函数上使用两次,然后将结果组合到一个列表中。scipy.integrate.quad 的文档给出了要集成的函数的可能签名,每个签名都表明该函数必须返回一个double
值(float
在 Python 中调用),而不是一个列表。
如果您无法更改 or 的定义time_start
或fun
的参数或返回值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_start
andfun
作为全局变量,而不是作为 的参数integral
,也是不好的做法,但我坚持你使用它们的方式。
推荐阅读
- c++ - 如何在 C++ 类中实现在 C 标头中使用“extern”子句指定的函数?
- python-3.x - 有没有办法从 S3 下载 N 个文件作为一个文件?
- django - 使用'unique'的翻译字段会增加NameError,django-parler
- arrays - C动态增长数组重新分配问题
- oracle - 在月底中断相等的周期
- algorithm - 以纯粹的功能方式使用 BFS 在球拍中实现最短路径?
- python - 如何使用 Poetry 将 Python 包发布到 CodeArtifact?
- python - 如何无限循环函数输出图形上坐标的象限
- python - 我正在尝试通过函数将任何 dict 转换为列表,但它不起作用并且无法找出原因
- git - 当存储库位于受保护的网络驱动器上时,Visual Studio 2019 团队资源管理器无法添加本地 Git 存储库