【问题标题】:What's the pythonic way to integrate a function that returns an array (using scipy quad)?集成返回数组的函数的pythonic方法是什么(使用scipy quad)?
【发布时间】:2015-10-30 18:11:58
【问题描述】:

我有一个返回数组的函数:

def fun(x,a):
    return [a*x,a*x**2]

我想集成它(使用 scipy quad):

def integrate(a):
    return quad(fun[0],0,1,args=a)
print integrate(1)

这给了TypeError: 'function' object is not subscriptable
什么是正确的 Pythonic 方式来做到这一点?

【问题讨论】:

  • 所以你想通过ax整合?
  • fun[0] 正在尝试下标该函数。你想给函数的结果下标吗?在这种情况下,语法是 fun(param1, param2)[0]
  • @tzaman: 是的,整合第一个(或任何其他)数组元素
  • @RobertB: 'quad(fun(x,a)[0],0,1,args=a)' 给出 'NameError: global name 'x' is not defined'
  • 看'quad',第一个参数是一个函数。所以fun 是你的功能,而不是fun[0]。另外,不要调用第二个函数“int”,因为这会破坏命名空间中的标准 python“int”类型。

标签: python arrays scipy


【解决方案1】:

围绕fun 创建一个包装函数以选择数组的一个元素。例如,下面将整合数组的第一个元素。

from scipy.integrate import quad

# The function you want to integrate
def fun(x, a):
    return np.asarray([a * x, a * x * x])

# The wrapper function
def wrapper(x, a, index):
    return fun(x, a)[index]

# The integration
quad(wrapper, 0, 1, args=(1, 0))

按照@RobertB 的建议,您应该避免定义函数int,因为它会与内置名称混淆。

【讨论】:

  • 我认为“包装器”可能是错误的术语,但解决方案足够有效
  • @Stick,你有什么建议作为替代方案?很高兴做出改变。
  • imho - 这只是一个调用另一个函数的函数。包装器会建议您可以使用@my_func 语法或使用附件或其他东西的情况,对吗?
  • 这是其中的一部分,但是您不能在示例中使用装饰器(这是我不知道将其称为“包装器函数”的部分原因,它不包装任何东西) .它真的不会改变答案的有效性,所以它可能并不重要
【解决方案2】:

你的函数返回一个数组,integrate.quad 需要一个浮点数来集成。所以你想给它一个函数,从你的数组中返回一个元素,而不是函数本身。您可以通过快速lambda 做到这一点:

def integrate(a, index=0)
    return quad(lambda x,y: fun(x, y)[index], 0, 1, args=a)

【讨论】:

  • 在这个答案中,我不鼓励 OP 定义一个名为 'int' 的函数,因为这会破坏 'int' 类型。我知道这是 OP 所做的,但在您的回答中,也许您可​​以使用不同的名称?
猜你喜欢
  • 2014-09-06
  • 2013-06-08
  • 1970-01-01
  • 2019-06-28
  • 2014-11-28
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多