Say I have a function f(x) = a*x which I'd like to integrate over x for a given a. I want to be able to pass scipy.integrate.quad an array of arg 'a' to iterate over. 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". 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. What do you suggest I do?
Try quad_vec: https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad_vec.html
Also don't forget a comma for an argument tuple: args=(i, )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.