# 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, pend.pos, 0), radius=0.1)
pend2 = sphere(pos=(-2, -L, 0), radius=1, color=color.red)
rod2 = cylinder(pos=(-2, 0, 0), axis=(pend2.pos+2, pend2.pos, 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, pend.pos, 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 + 2, pend2.pos, 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.

Posted in Python

### 3 Responses to Newton’s Cradle in Visual Python

1. Shailesh Sarda says:

Than calculate kinetic energy and plot it .

• leonh says:

It sounds like a fun project, but I am sorry, I cannot help.

2. mariesmith says:

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

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

Follow