Search code examples
numpymatplotlibderivative

Represent a first order differential equation in numpy


I have an equation dy/dx = x + y/5 and an initial value, y(0) = -3.

I would like to know how to plot the exact graph of this function using pyplot.

I also have a x = np.linspace(0, interval, steps+1) which I would like to use as the x axis. So I'm only looking for the y axis values.

Thanks in advance.


Solution

  • Just for completeness, this kind of equation can easily be integrated numerically, using scipy.integrate.odeint.

    import numpy as np
    from scipy.integrate import odeint
    import matplotlib.pyplot as plt
    
    # function dy/dx = x + y/5.
    func = lambda y,x : x + y/5.
    # Initial condition
    y0 = -3  # at x=0
    # values at which to compute the solution (needs to start at x=0)
    x = np.linspace(0, 4, 101)
    # solution
    y = odeint(func, y0, x)
    # plot the solution, note that y is a column vector
    plt.plot(x, y[:,0])
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()
    

    enter image description here