Search code examples
pythonnumpyintegral

Definite Integral using numpy.trapz?


I have a function defined as:

def probability(x,t,i):
    return np.real(np.conjugate(TD_Psi(x,t,i))*TD_Psi(x,t,i))

I've so far used the following method of integration in python

  for t in range(0,10):
            PD = (np.trapz(probability(x,t,initial_state),x))
            print (PD)

Is there any way I can adjust this to integrate over certain values of x for example from x = 0 to x = 5?


Solution

  • You specify the integration range when you pass the x array to the np.trapz function. In order to integrate from 0 to 5, using for instance 1000 function values in that range, you should do

    x = np.linspace(0,5,1000)
    for t in range(0,10):
        PD = (np.trapz(probability(x,t,initial_state),x))
        print (PD)