python - Scipy: efficiently generate a series of integration (integral function) -
i have function, want integral function, this:
that is, instead of getting single integration value @ point x, need values @ multiple points.
for example:
let's want range @ (-20,20)
def f(x): return x**2 x_vals = np.arange(-20, 21, 1) y_vals =[integrate.nquad(f, [[0, x_val]]) x_val in x_vals ] plt.plot(x_vals, y_vals,'-', color = 'r') the problem
in example code give above, each point, integration done scratch. in real code, f(x) pretty complex, , it's multiple integration, running time slow(scipy: speed integration when doing whole surface?).
i'm wondering if there way of efficient generating phi(x), @ giving range.
my thoughs:
the integration value @ point phi(20) calucation phi(19), , phi(19) phi(18) , on. when phi(20), in reality series of (-20,-19,-18,-17 ... 18,19,20). except didn't save value.
so i'm thinking, possible create save points integrate function, when passes save point, value saved , continues next point. therefore, single process toward 20, value @ (-20,-19,-18,-17 ... 18,19,20)
one could implement strategy outlined integrating on short intervals (between consecutive x-values) , taking cumulative sum of results. this:
import numpy np import scipy.integrate si def f(x): return x**2 x_vals = np.arange(-20, 21, 1) pieces = [si.quad(f, x_vals[i], x_vals[i+1])[0] in range(len(x_vals)-1)] y_vals = np.cumsum([0] + pieces) here pieces integrals on short intervals, summed produce y-values. written, code outputs function 0 @ beginning of range of integration -20. 1 can, of course, subtract y-value corresponds x=0 in order have same normalization on plot.
that said, split-and-sum process unnecessary. when find indefinite integral of f, solving differential equation f' = f. , scipy has built-in method that, odeint. use it:
import numpy np import scipy.integrate si def f(x): return x**2 x_vals = np.arange(-20, 21, 1) y_vals = si.odeint(lambda y,x: f(x), 0, x_vals) the output essential identical first version (within tiny computational errors), less code. reason using lambda y,x: f(x) first argument of odeint must function taking 2 arguments, right-hand side of equation y' = f(y, x).


Comments
Post a Comment