Passing arguments to mpmath quad integration
I'm integrating some pretty nasty functions, and scipy.integrate.quad开发者_Go百科 is not handling the situation very well. I was planning to use mpmath.quad with tanh-sinh method, but I need to pass some arguments to the function that is being calculated, like this:
mpmath.quad(f,[0,mpmath.pi],method='tanh-sinh',args=(arg_1, arg_2))
as f is defined as
f(x,arg_1, arg_2)
Didn't find anything like that on the doc. Any suggestions?
Thanks!
Use lambda:
import mpmath
arg_1 = 1
arg_2 = 9
print mpmath.quad(lambda x: f(x, arg_1, arg_2), ...)
Just a hint that tanh-sinh quadrature is also available without mpmath, via tanh_sinh (one of my packages). If your function has extra parameters, you can always just wrap the function, like so:
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)
I like this approach better than passing the args because it's more explicit.
精彩评论