Search code examples
pythonnumpymatplotlibscipyodeint

How to solve a differential equation for different initial conditions


I want to solve a differential equation continuously by changing the initial conditions only. I have tried a lot but didn't find any suitable process to do that properly. Can anyone please share any idea about that. For your kind consideration I'm giving below the code that could solve the differential equation:

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt


c = 1.0   #value of constants

#define function
def exam(y, x):
    theta, omega = y
    dydx = [omega, - (2.0/x)*omega - theta**c]
    return dydx


#initial conditions
y0 = [1.0, 0.0] ## theta, omega

x = np.linspace(0.1, 10, 100)

#call integrator
sol = odeint(exam, y0, x)

plt.plot(x, sol[:, 0], 'b')
plt.legend(loc='best')
plt.grid()
plt.show()

So, my query is how can I solve the above differential equation for different initial conditions at a time (suppose for y = [1.0, 0.0]; y = [1.2, 0.2]; y = [1.3, 0.3]) and plot them together.


Solution

  • So you can use a function and loop through the initial values. Just make sure you have your list of y0s in the correct format to loop though. Using a function you could also specify changes to c.

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.integrate import odeint
    
    
    def solveit(c,y0):
        def exam(y, x):
            theta, omega = y
            dydx = [omega, - (2.0/x)*omega - theta**c]
            return dydx
        #initial conditions
    #    y0 = [1.0, 0.0] ## theta, omega
    
        x = np.linspace(0.1, 10, 100)
    
        #call integrator
        sol = odeint(exam, y0, x)
    
        plt.plot(x, sol[:, 0], label='For c = %s, y0=(%s,%s)'%(c,y0[0],y0[1]))
    
    
    
    
    ys= [[1.0, 0.0],[1.2, 0.2],[1.3, 0.3]]
    
    fig = plt.figure()
    for y_ in ys:
        solveit(c=1.,y_)
    
    plt.legend(loc='best')
    plt.grid()
    plt.show()
    

    enter image description here