Newton’s Cradle in Visual Python

Feb, 18, 2017

This simple program shows an animation of a two-pendulum version of Newton’s cradle. One pendulum begins at some starting angle and the other pendulum is stationary. When the moving pendulum slams into the stationary one, its momentum is transferred to the other pendulum.

from visual import *
import numpy as np

# Constants
g = 9.80            # (m/s^2)
L = 10              # Length of the pendulums (m)
initialAngle = 1.2  # In radians

# Create the pendulum bob and rod
pend = sphere(pos=(L*np.sin(initialAngle), -L*np.cos(initialAngle), 0), radius=1, color=color.yellow)
rod = cylinder(pos=(0, 0, 0), axis=(pend.pos[0], pend.pos[1], 0), radius=0.1)
pend2 = sphere(pos=(-2, -L, 0), radius=1,
rod2 = cylinder(pos=(-2, 0, 0), axis=(pend2.pos[0]+2, pend2.pos[1], 0), radius=0.1)

def position(right, t):
    Only one of the pendulums is in motion at a given time. This function
    moves the moving pendulum to its new position. We use the equation:
        theta(t) = theta_0*cos(sqrt(g/L)*t)
    theta = initialAngle*np.cos((g/L)**(1/2)*t)

    if right:
        pend.pos = [L * np.sin(theta), -L * np.cos(theta), 0]  # Update position of bob
        rod.axis = [pend.pos[0], pend.pos[1], 0]  # Update rod's position
        pend2.pos = [L * np.sin(theta) - 2, -L * np.cos(theta), 0]  # Update position of bob
        rod2.axis = [pend2.pos[0] + 2, pend2.pos[1], 0]  # Update rod's position

    # Once the moving pendulum reaches theta = 0, switch to the other one
    if theta <= 0:
        return False  # Return
        return True

# Increment time
i = 0
right = True  # The right pendulum is the first in motion
while True:
    right = position(right, i)
    i += 0.01

If you want to include damping, you can change the line

theta = initialAngle*np.cos((g/L)**(1/2)*t)


theta = initialAngle*exp(-mu*t)*np.cos((g/L)**(1/2)*t)

with some value for mu.


Posted in Python | 3 Comments

3 Responses to Newton’s Cradle in Visual Python

  1. Shailesh Sarda says:

    Can you please help me to solve differential equations that describes Newton’s cradle motion using python to plot graphics (displacement and velocity)
    Than calculate kinetic energy and plot it .

  2. mariesmith says:

    Awesome! Is there any way to get a tutorial to do one with three or more pendulums?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Get every new post on this blog delivered to your Inbox.

Join other followers: