scipy.integrate.romberg - 如何使用关键字参数传递函数

时间:2015-02-02 20:49:45

标签: python scipy numerical-integration

希望这是一个快速,简单的问题,但它让我有点困惑......

我有一个函数,它需要两个强制参数和几个我想用scipy.integrate.romberg集成的关键字参数。我知道我可以使用scipy.integrate.romberg关键字向args传递额外的参数,我可以在其中指定额外的参数作为元组,但是,在元组中,我如何指定哪个函数参数是关键字参数,哪个是关键字参数吗?

e.g。

import numpy as np
from scipy import integrate

def myfunc(x,y,a=1,b=2):
    if y > 1.0:
         c = (1.0+b)**a
    else:
         c = (1.0+a)**b
    return c*x

y = 2.5
a = 4.0
b = 5.0

integral = integrate.romberg(myfunc,1,10,...?) # What do I specify here so
                                               # that romberg knows that 
                                               # y = 2.5, a = 4.0, b = 5.0?

首先我尝试在一个类中定义函数,以便所有关键字参数都在__init__中设置,但scipy.integrate.romberg似乎不喜欢我传递一个函数{{1作为第一个参数。 (现在我恐怕没有错误消息)!

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

对原始帖子的评论建议将关键字参数作为位置参数传递。这样做会有效,但如果有很多关键字参数并且你不想明确地传递它们,那将会很麻烦。更通用(也许更Pythonic)的方法是使用这样的闭包来包装你的函数:

def myfunc(x,y,a=1,b=2):
    if y > 1.0:
         c = (1.0+b)**a
    else:
         c = (1.0+a)**b
    return c*x

def mywrapper(*args, **kwargs):
    def func(x):
        return myfunc(x, *args, **kwargs)
    return func

myfunc_with_args = mywrapper(2.5, a=4.0, b=5.0)
integral = integrate.romberg(myfunc_with_args, 1, 10)