1

我正在集成一些非常讨厌的功能,而 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)

在文档上没有找到类似的东西。有什么建议么?

谢谢!

4

2 回答 2

2

使用 lambda:

import mpmath
arg_1 = 1
arg_2 = 9

print mpmath.quad(lambda x: f(x, arg_1, arg_2), ...)
于 2011-06-06T18:39:08.517 回答
1

通过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)

我比传递参数更喜欢这种方法,因为它更明确。

于 2020-05-16T11:01:45.800 回答