import numpy as np %pylab inline import matplotlib.pyplot as plt # JSAnimation import available at https://github.com/jakevdp/JSAnimation from JSAnimation import IPython_display from matplotlib import animation #RK2 integrator def RK2_step( f, y, t, h ): #Creating solutions K0 = h*f(t, y) K1 = h*f(t + 0.5*h, y + 0.5*K0) y1 = y + K1 #Returning solution return y1 #======================================================== #Defining parameters #======================================================== #Gravity g = 9.8 #Pendulum's lenght l = 1.0 #Number of initial conditions Nic = 1000 #Maxim angular velocity omega_max = 8 #Maxim time of integration tmax = 6*np.pi #Timestep h = 0.01 #======================================================== #Dynamical function of the system #======================================================== def function( t, y ): #Using the convention y = [theta, omega] theta = y[0] omega = y[1] #Derivatives dtheta = omega domega = -g/l*np.sin(theta) return np.array([dtheta, domega]) #======================================================== #Generating set of initial conditions #======================================================== theta0s = -4*np.pi + np.random.random(Nic)*8*np.pi omega0s = -omega_max + np.random.random(Nic)*2*omega_max #======================================================== #Integrating and plotting the solution for each IC #======================================================== #Setting figure plt.figure( figsize = (8,5) ) for theta0, omega0 in zip(theta0s, omega0s): #Arrays for solutions time = [0,] theta = [theta0,] omega = [omega0,] for i, t in zip(xrange(int(tmax/h)), np.arange( 0, tmax, h )): #Building current condition y = [theta[i], omega[i]] #Integrating the system thetai, omegai = RK2_step( function, y, t, h ) #Appending new components theta.append( thetai ) omega.append( omegai ) time.append( t ) #Plotting solution plt.plot( theta, omega, lw = 0.1, color = "black" ) #Format of figure plt.xlabel( "$\\theta$", fontsize = 18 ) plt.ylabel( "$\omega$", fontsize = 18 ) plt.xlim( (-2*np.pi, 2*np.pi) ) plt.ylim( (-omega_max, omega_max) ) plt.title( "Phase space of a pendulum" ) plt.grid(1)