简体   繁体   English

迭代 scipy.integrate 中的 args 数组而不使用 for 循环

[英]Iterate over array of args in scipy.integrate without for-loops

Say I have a function f(x) = a*x which I'd like to integrate over x for a given a.假设我有一个 function f(x) = a*x,我想对给定的 a 对 x 进行积分。 I want to be able to pass scipy.integrate.quad an array of arg 'a' to iterate over.我希望能够通过 scipy.integrate.quad 一个 arg 'a' 数组进行迭代。 For just one parameter I know this can be done via对于一个参数,我知道这可以通过

import numpy as np
from scipy import integrate
param = 1 
def f(x,a):
    return a*x
integral = integrate.quad(f,0,1,args = (param)) # 0,1 are just arbitrary limits of integration
print(integral)

which works as expected.按预期工作。 However, if I want to iterate over an array of param values, ex.)但是,如果我想遍历一个参数值数组,例如)

param = np.array([1,2])
def f(x,a):
    return a*x
integral = integrate.quad(f,0,1,args = (param))
print(integral)

I get the error: "only size-1 arrays can be converted to Python scalars".我收到错误消息:“只有 size-1 arrays 可以转换为 Python 标量”。 Obviously I can avoid this by implementing something like显然我可以通过实现类似的东西来避免这种情况

integrals = []
for i in param:
    integrals.append(integrate.quad(f,0,1,args = (i)))

but I'd like to avoid for-loops where possible in the interest of keeping the code fast for larger sized param arrays and multiple integrals.但我想尽可能避免使用 for 循环,以便为较大的参数 arrays 和多重积分保持快速的代码。 What do you suggest I do?你建议我怎么做?

Try quad_vec: https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad_vec.html试试 quad_vec: https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad_vec.ZFC35FDC70D5FC69D269883A822C7A53

Also don't forget a comma for an argument tuple: args=(i, )也不要忘记参数元组的逗号: args=(i, )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM