我正在集成一些非常讨厌的功能,而 scipy.integrate.quad 并没有很好地处理这种情况。我打算将 mpmath.quad 与 tanh-sinh 方法一起使用,但我需要将一些参数传递给正在计算的函数,如下所示:
mpmath.quad(f,[0,mpmath.pi],method='tanh-sinh',args=(arg_1, arg_2))
因为 f 被定义为
f(x,arg_1, arg_2)
在文档上没有找到类似的东西。有什么建议么?
谢谢!
使用 lambda:
import mpmath
arg_1 = 1
arg_2 = 9
print mpmath.quad(lambda x: f(x, arg_1, arg_2), ...)
通过tanh_sinh(我的软件包之一)提示 tanh-sinh 求积也可以在没有 mpmath 的情况下使用。如果你的函数有额外的参数,你总是可以只包装函数,如下所示:
import tanh_sinh
import numpy
def fun(x, a):
return a * numpy.exp(x) * numpy.cos(x)
val, error_estimate = tanh_sinh.integrate(
lambda x: fun(x, 1),
0,
numpy.pi / 2,
1.0e-14,
# Optional: Specify first and second derivative for better error estimation
# f_derivatives={
# 1: lambda x: numpy.exp(x) * (numpy.cos(x) - numpy.sin(x)),
# 2: lambda x: -2 * numpy.exp(x) * numpy.sin(x),
# },
)
print(val, error_estimate)
我比传递参数更喜欢这种方法,因为它更明确。