COMPUTER PROBLEMS 6.3

\(\def\ds{\displaystyle} \) 1 (a) The code euler2.py in Program 6.2 can be used to calculate the two approximations, for step sizes \(h=0.1\) and \(h=0.01\). For \(h=0.1\), the global truncation errors are \([0.1973, 0.1592]\) for \(w_{n1}\) and \(w_{n2}\), \(n=10\). For \(h=0.01\), the global truncation errors are \([0.0226, 0.0149]\) for \(w_{n1}\) and \(w_{n2}\), \(n=100\). The errors decrease by roughly a factor of 10 for the smaller step size, as expected for a first order method. The plots of the two approximations and the correct solution (dashed) are below.


1 (b) Similar to (a). The global truncation errors are \([0.0328, 0.0219]\) for step size \(h=0.1\), and \([0.0031, 0.0020]\) for \(h=0.01\).


1 (c) Similar to (a). The global truncation errors are \([0.0305, 0.0410]\) for step size \(h=0.1\), and \([0.0027, 0.0042]\) for \(h=0.01\).


1 (d) Similar to (a). The global truncation errors are \([51.4030, 51.3070]\) for step size \(h=0.1\), and \([8.1919, 8.1827]\) for \(h=0.01\).



3 To modify pend to exhibit damping, add the term \(-dy_2\) to the \(y_2'\) equation in the ydot function, where \(d=0.1\). All initial conditions lead toward the straight-down position of the pendulum, except for the straight-up position \(y_1(0)=\pi, y_2(0)=0\). In theory, this position is an unstable steady-state, meaning that it will never move unless there is a small outside perturbation. For a physical pendulum, small perturbations will occur, and the pendulum will fall from the up position. The outcome of the simulation with pend depends on the step size and the fact that \(\sin \pi\) is not exactly zero. It differs on the order of machine epsilon, providing the perturbation needed, at least when step size \(h=0.05\) is used, to cause the pendulum to fall and eventually move to the straight-down position as a physical pendulum would.
5 To modify pend to exhibit periodic forcing and damping, add the term \(-dy_2+A\sin t\) to the \(y_2'\) equation in the ydot function, where \(d=1\) and \(A=12\). After waiting for transient effects to die down, the pendulum will settle into one of two stable trajectories. One of them makes three and one-half clockwise revolutions followed by two and one-half counterclockwise revolutions, and repeats. The other does the same, replacing clockwise with counterclockwise. For example, the initial condition \((y_1, y_2)=(0.2, 0)\) settles into the first motion, and the initial condition \((y_1, y_2)=(0.15, 0)\) converges to the second.
7 The ydot function in pend.py must be modified to solve the system \begin{eqnarray*} y_1'&=&y_2\\ y_2'&=& \left(-\frac{g}{l}+A\cos 2\pi t \right)\sin y_1-dy_2 \end{eqnarray*} where \(g=9.81, l=2.5\). Starting with an initial position that is close to, but not exactly, zero (for example, \((y_1,y_2)=(0.01,0)\)), one finds that for \(A\) above \(13.2\), the downward position is unstable as defined in the Computer Problem, in that the pendulum travels through the upward position.
9 To adjust orbit.py to solve the two-body problem, the stationary sun must be changed into a moving body. Some example code:
import numpy as np
import matplotlib.pyplot as plt

def orbit(inter, ic, n, p):
    """
    Input:  inter time interval
            ic initial conditions [x0,vx0,y0,vy0]
            n number of steps
            p step per plotted point
    Output: t time points
            traj orbital trajectory
    """
    h = (inter[1] - inter[0]) / n  # Step size
    x00, vx00, y00, vy00,x10,vx10,y10,vy10 = ic  # Initial conditions
    traj = np.zeros((n+1, 8))  # Initialize position and velocity array
    y = np.zeros((p+1, 8))
    y[0, :] = [x00, vx00, y00, vy00,x10, vx10, y10, vy10]
    t = np.zeros((n+1))  # Time array
    t[0] = inter[0]
    plt.figure()
    plt.xlim(-5, 5)
    plt.ylim(-5, 5)
    #plt.plot(0, 0, 'yo', markersize=16) # Draw sun at origin
    # Prepare line objects for head and tail of the orbit
    head1, = plt.plot([], [], 'ro', markersize=8)
    tail1, = plt.plot([], [], 'b-', linestyle='-', markersize=4)
    head2, = plt.plot([], [], 'yo', markersize=8)
    tail2, = plt.plot([], [], 'b-', linestyle='-', markersize=4)
    plt.ion()  # Enable interactive mode for real-time plotting
    for k in range(n // p):
        for i in range(p):
            t[k*p+i+1] = t[k*p+i] + h
            y[i + 1, :] = trapstep(ydot, t[i], y[i, :], h)
        traj[k*p+1:(k+1)*p+1,:] = y[1:,:]
        # Update the position for the next frame
        set_position(head1, y[p, 0], y[p, 2])  # Update head position
        set_position(tail1, traj[1:(k+1)*p+1, 0], traj[1:(k+1)*p+1, 2]) 
        set_position(head2, y[p, 4], y[p, 6])  # Update head position
        set_position(tail2, traj[1:(k+1)*p+1, 4], traj[1:(k+1)*p+1, 6]) 
        y[0, :] = y[p, :]  # Update last computed position
        plt.draw()
        plt.pause(0.01)  # Pause to visualize updates
    plt.ioff()  # Disable interactive mode
    plt.show()  # Show the plot window
    return t, traj

def eulerstep(ydot, t, x, h): return x + h*ydot(t, x)

def trapstep(ydot, t, y, h): return y + h/2.*(ydot(t, y)+ydot(t+h,y+h*ydot(t,y)))


def ydot(t, x):
    m0 = 0.03
    m1 = 0.3  # Mass of the second object
    g = 1   # Gravitational acceleration
    mg0,mg1 = m0*g,m1*g
    px0,vx0,py0,vy0,px1,vx1,py1,vy1 = x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7]  # Unpack values
    dist = np.sqrt((px1 - px0)**2 + (py1 - py0)**2)
    z = np.zeros(8)
    z[0] = vx0
    z[1] = (mg1*(px1 - px0))/(dist**3)  # Acceleration in x
    z[2] = vy0
    z[3] = (mg1*(py1 - py0))/(dist**3)  # Acceleration in y
    z[4] = vx1
    z[5] = (mg0*(px0 - px1))/(dist**3)  # Acceleration in x
    z[6] = vy1
    z[7] = (mg0*(py0 - py1))/(dist**3)  # Acceleration in y
    return z


def set_position(line, xdata, ydata):
    line.set_data(xdata, ydata)  # Function to set the position of plot points

# Example usage
orbit([0, 100], [2,0.2,2,-0.2,0,-0.02,0,0.02], 10000, 5)

11 Using the code from Computer Problem 9, one can run

    orbit([0, 100], [0,0.2,1,-0.2,-2,-0.2,-1,0.2], 10000, 5) 
    

along with the given masses. The orbits have some near passes, at which extra precision is needed to preserve accuracy.


13 Code follows:
import numpy as np
import matplotlib.pyplot as plt

def orbit(inter, ic, n, p):
    """
    Input:  inter time interval
            ic initial conditions [x0,vx0,y0,vy0]
            n number of steps
            p step per plotted point
    Output: t time points
            traj orbital trajectory
    """
    h = (inter[1] - inter[0]) / n  # Step size
    x00, vx00, y00, vy00,x10,vx10,y10,vy10,x20,vx20,y20,vy20  = ic  # Initial conditions
    traj = np.zeros((n+1, 12))  # Initialize position and velocity array
    y = np.zeros((p+1, 12))
    y[0, :] = [x00, vx00, y00, vy00, x10, vx10, y10, vy10, x20, vx20, y20, vy20]
    t = np.zeros((n+1))  # Time array
    t[0] = inter[0]
    plt.figure()
    plt.xlim(-5, 5)
    plt.ylim(-5, 5)
    #plt.plot(0, 0, 'yo', markersize=16) # Draw sun at origin
    # Prepare line objects for head and tail of the orbit
    head0, = plt.plot([], [], 'ro', markersize=8)
    tail0, = plt.plot([], [], 'b-', linestyle='-', markersize=4)
    head1, = plt.plot([], [], 'yo', markersize=8)
    tail1, = plt.plot([], [], 'b-', linestyle='-', markersize=4)
    head2, = plt.plot([], [], 'ko', markersize=8)
    tail2, = plt.plot([], [], 'b-', linestyle='-', markersize=4)
    plt.ion()  # Enable interactive mode for real-time plotting
    for k in range(n // p):
        for i in range(p):
            t[k*p+i+1] = t[k*p+i] + h
            y[i+1, :] = trapstep(ydot, t[i], y[i, :], h)
        traj[k*p+1:(k+1)*p+1,:] = y[1:,:]
        # Update the position for the next frame
        set_position(head0, y[p, 0], y[p, 2])  # Update head position
        set_position(tail0, traj[1:(k+1)*p+1, 0], traj[1:(k+1)*p+1, 2]) 
        set_position(head1, y[p, 4], y[p, 6])  # Update head position
        set_position(tail1, traj[1:(k+1)*p+1, 4], traj[1:(k+1)*p+1, 6]) 
        set_position(head2, y[p, 8], y[p, 10])  # Update head position
        set_position(tail2, traj[1:(k+1)*p+1, 8], traj[1:(k+1)*p+1, 10]) 
        y[0, :] = y[p, :]  # Update last computed position
        plt.draw()
        plt.pause(0.01)  # Pause to visualize updates
    plt.ioff()  # Disable interactive mode
    plt.show()  # Show the plot window
    return t, traj

def eulerstep(ydot, t, x, h): return x + h*ydot(t, x)

def trapstep(ydot, t, y, h): return y + h/2.*(ydot(t, y)+ydot(t+h,y+h*ydot(t,y)))


def ydot(t, x):
    m0 = 0.05
    m1 = 0.5
    m2 = 1e-4
    g = 1   # Gravitational acceleration
    mg0,mg1,mg2 = m0*g,m1*g,m2*g
    px0,vx0,py0,vy0,px1,vx1,py1,vy1,px2,vx2,py2,vy2 = x[0],x[1],x[2],x[3],x[4],x[5],x[6],x[7],x[8],x[9],x[10],x[11]  # Unpack values
    dist01 = np.sqrt((px1 - px0)**2 + (py1 - py0)**2)
    dist02 = np.sqrt((px2 - px0)**2 + (py2 - py0)**2)
    dist12 = np.sqrt((px2 - px1)**2 + (py2 - py1)**2)
    z = np.zeros(12)
    z[0] = vx0
    z[1] = mg1*(px1 - px0)/(dist01**3) + mg2*(px2 - px0)/(dist02**3)
    z[2] = vy0
    z[3] = mg1*(py1 - py0)/(dist01**3) + mg2*(py2 - py0)/(dist02**3)
    z[4] = vx1
    z[5] = mg0*(px0 - px1)/(dist01**3) + mg2*(px2 - px1)/(dist12**3)
    z[6] = vy1
    z[7] = mg0*(py0 - py1)/(dist01**3)  + mg2*(py2 - py1)/(dist12**3)
    z[8] = vx2
    z[9] = mg0*(px0 - px2)/(dist02**3) + mg1*(px1 - px2)/(dist12**3)
    z[10] = vy2
    z[11] = mg0*(py0 - py2)/(dist02**3) + mg1*(py1 - py2)/(dist12**3)
    return z


def set_position(line, xdata, ydata):
    line.set_data(xdata, ydata)  # Function to set the position of plot points

# Example usage
orbit([0, 100], [0,.1,1,-.1,-2,-0.01,-1,.01,4,-.2,3,0], 10000, 5)

15 The code above can be used with adjusted masses and initial conditions to show this three-body orbit.