Scipy: efficiently generate a series of integrations (integral function)

I have a function, I want to get its integral function, something like this:

enter image description here

That is, instead of getting a single integration value at a point, xI need to get the values ​​at multiple points.

For example:

Say I want a range in (-20.20)

def f(x):
    return x**2

x_vals  = np.arange(-20, 21, 1)
y_vals =[integrate.nquad(f, [[0, x_val]]) for x_val in x_vals ]

plt.plot(x_vals, y_vals,'-', color = 'r')

enter image description here

Problem

In the above code example, for each point, integration is performed from scratch . In my real code, it’s f(x)quite complicated and it’s multiple integration, so the runtime is just too slow ( Scipy: speed up integration by doing this for the whole surface? ).

I am wondering if there is a way to efficiently generate Phi(x)in a date range.

My notes:

Phi(20) - Phi(19), Phi(19) - Phi(18) .. , Phi(20), (-20,-19,-18,-17 ... 18,19,20). , .

, , , , save point, . 20 (-20,-19,-18,-17 ... 18,19,20)

+4
1

, , ( ), . :

import numpy as np
import scipy.integrate as 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] for i in range(len(x_vals)-1)]
y_vals = np.cumsum([0] + pieces)

pieces - , y. , , 0 , -20. , y, x = 0, , .

, . f, F '= f. SciPy , odeint. :

import numpy as np
import scipy.integrate as 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)

( ) . lambda y,x: f(x) , odeint , , y '= f (y, x).

+2

Source: https://habr.com/ru/post/1627534/


All Articles