# importrequired libraries import numpy import matplotlib.pyplot as plt %matplotlib inline # set the initial parameters alpha = 1. beta = 1.2 gamma = 4. delta = 1. #define the time stepping scheme - euler forward, as used in earlier lessons def euler_step(u, f, dt): """Returns the solution at the next time-step using Euler's method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equation. dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ return u + dt * f(u) # define the function that represents the Lotka-Volterra equations def f(u): """Returns the rate of change of species numbers. Parameters ---------- u : array of float array containing the solution at time n. Returns ------- dudt : array of float array containing the RHS given u. """ x = u[0] y = u[1] return numpy.array([x*(alpha - beta*y), -y*(gamma - delta*x)]) # set time-increment and discretize the time T = 15.0 # final time dt = 0.01 # set time-increment N = int(T/dt) + 1 # number of time-steps x0 = 10. y0 = 2. t0 = 0. # set initial conditions u_euler = numpy.empty((N, 2)) # initialize the array containing the solution for each time-step u_euler[0] = numpy.array([x0, y0]) # use a for loop to call the function rk2_step() for n in range(N-1): u_euler[n+1] = euler_step(u_euler[n], f, dt) time = numpy.linspace(0.0, T,N) x_euler = u_euler[:,0] y_euler = u_euler[:,1] plt.plot(time, x_euler, label = 'prey ') plt.plot(time, y_euler, label = 'predator') plt.legend(loc='upper right') #labels plt.xlabel("time") plt.ylabel("number of each species") #title plt.title("predator prey model") plt.plot(x_euler, y_euler, '-->', markevery=5, label = 'phase plot') plt.legend(loc='upper right') #labels plt.xlabel("number of prey") plt.ylabel("number of predators") #title plt.title("predator prey model") def RK4(u,f,dt): # Runge Kutta 4th order method """Returns the solution at the next time-step using Runge Kutta fourth order (RK4) method. Parameters ---------- u : array of float solution at the previous time-step. f : function function to compute the right hand-side of the system of equation. dt : float time-increment. Returns ------- u_n_plus_1 : array of float approximate solution at the next time step. """ #calculate slopes k1 = f(u) u1 = u + (dt/2.)*k1 k2 = f(u1) u2 = u + (dt/2.)*k2 k3 = f(u2) u3 = u + dt*k3 k4 = f(u3) return u + (dt/6.)*(k1 + 2.*k2 + 2.*k3 + k4) from IPython.core.display import HTML css_file = '../../styles/numericalmoocstyle.css' HTML(open(css_file, "r").read())