# Newton’s Cradle in Visual Python

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, color=color.red)
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
else:
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
else:
return True

# Increment time
i = 0
right = True  # The right pendulum is the first in motion
while True:
rate(200)
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)

to

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

with some value for mu.

## 3 thoughts on “Newton’s Cradle in Visual Python”

1. Shailesh Sarda says: