0% found this document useful (0 votes)
6 views

rr

The document outlines the development of an Interactive Pendulum Simulation using Python and the pygame library, aimed at educating users about pendulum dynamics under varying gravitational conditions. It details the project's aims, objectives, literature review, and the implementation of the simulation, which allows real-time interaction and analysis of swing times. The simulation incorporates key physics principles and provides an engaging platform for users to learn about the effects of gravity and damping on pendulum motion.

Uploaded by

Ayesha Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

rr

The document outlines the development of an Interactive Pendulum Simulation using Python and the pygame library, aimed at educating users about pendulum dynamics under varying gravitational conditions. It details the project's aims, objectives, literature review, and the implementation of the simulation, which allows real-time interaction and analysis of swing times. The simulation incorporates key physics principles and provides an engaging platform for users to learn about the effects of gravity and damping on pendulum motion.

Uploaded by

Ayesha Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Contents

1. INTRODUCTION................................................................................................................................... 2
2. AIMS AND OBJECTIVES .................................................................................................................... 2
2.1 Aims: .................................................................................................................................................. 2
2.2 Objectives: ......................................................................................................................................... 2
3. LITERATURE REVIEW ...................................................................................................................... 2
4. PROBLEM .............................................................................................................................................. 3
5. SOLUTION ............................................................................................................................................. 4
5.1 Devices/Equipment: .......................................................................................................................... 4
6. MODELING AND SIMULATION IMPLEMENTATION ........................................................ 4
6.1 Python VS Code ................................................................................................................................ 4
6.2 Modeling .......................................................................................................................................... 16
6.3 Key Functionalities in Code ........................................................................................................... 18
7. RESULTS .............................................................................................................................................. 18
7.1 Observations:................................................................................................................................... 18
7.2 Sample Output: ............................................................................................................................... 19
7.3 Graphs.............................................................................................................................................. 19
7.4 Derivation: ....................................................................................................................................... 25
8. DISCUSSION ........................................................................................................................................ 29
9. CONCLUSION ..................................................................................................................................... 29
10. REFERENCES .................................................................................................................................... 29

1
1. INTRODUCTION

The Interactive Pendulum Simulation is a Python-based application developed to model the motion
of a pendulum in real-time. Using the pygame library, this simulation provides an interactive
platform for visualizing the effects of gravitational forces on pendulum dynamics. It incorporates
key physics principles such as angular acceleration, damping, and gravity. The program also
allows users to interact with the pendulum, switch gravitational forces to simulate conditions on
different celestial bodies, and analyze swing times.

2. AIMS AND OBJECTIVES


2.1 Aims:

The primary aim of the project is to create an educational tool to help users understand pendulum
motion under varying conditions. It focuses on improving engagement with interactive features
and providing real-time feedback on physics-based simulations.

2.2 Objectives:

1. Simulate pendulum dynamics using realistic physics models.


2. Allow users to interact with the pendulum (drag, release, and reset).
3. Provide a platform to analyze swing times under different gravitational constants.
4. Enhance learning by demonstrating the impact of damping and gravity on pendulum behavior.

3. LITERATURE REVIEW

Pendulums have long been studied in physics due to their applications in timekeeping, mechanics,
and harmonic motion. This project draws upon classical physics concepts such as:

2
Reference Key Findings Method Limitations

Hughes, S., & Young, Demonstrates the A hybrid approach Simplified physics
M., 2024, May. impact of gravitational combining model, fixed
"Planets, spring, and force on pendulum numerical pendulum length,
pendulum." In motion, highlighting integration small-angle
Physics Education that higher gravity techniques for approximation,
(Vol. 59, No. 4). IOP causes faster, shorter pendulum motion. limited planetary
Publishing. swings while lower options, and no
gravity results in energy visualization.
slower, wider
oscillations.
Tufekci, S., & Koçak, Explores the use of Implemented using Limited interactivity,
E., 2022. "Simulation pendulum simulations physics-based no real-time
of pendulum motion as an educational tool equations with recording of swing
in educational to teach harmonic user-adjustable times, and
environments." motion concepts parameters for assumptions of ideal
Journal of Science effectively, gravity and energy conservation.
Education. emphasizing user damping.
interactivity to increase
engagement.
Kawaguchi, A., & Focuses on the role of Numerical Assumes uniform
Tanaka, H., 2020. damping in pendulum simulations with damping and neglects
"Impact of damping oscillations, showing added damping external forces such
on pendulum exponential decay in coefficients and as air resistance or
oscillations: A swing amplitude over real-time friction in the rope.
simulation time and how damping visualizations.
approach." Physics affects the energy
Review. transfer of the
pendulum.

4. PROBLEM

Traditional pendulum simulations often lack interactivity and real-world parameter variability,
limiting their ability to engage and educate users effectively. This project addresses this gap by
enabling users to modify gravitational constants, interact with the pendulum, and observe the
effects of damping and angular motion.

3
5. SOLUTION

The solution is an interactive pendulum simulation implemented in Python using the pygame
library. It provides:

1. A dynamic interface to visualize pendulum motion.


2. Real-time interaction through mouse dragging and releasing.
3. Analysis of swing times for different gravitational constants.

5.1 Devices/Equipment:

The simulation requires the following:

1. Hardware: Any computer capable of running Python


2. Software:
o Python
o pygame library for graphics and interaction.
o math and time libraries for physics calculations and timers.

6. MODELING AND SIMULATION IMPLEMENTATION

6.1 Python VS Code

The simulation was implemented using Python, with the following code:

import pygame

import math

import time

4
# Initialize pygame

pygame.init()

# Screen dimensions

WIDTH, HEIGHT = 1280, 720

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("Interactive Pendulum Simulation")

# Colors

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

RED = (255, 0, 0)

BLUE = (0, 0, 255)

DARK_GRAY = (50, 50, 50)

LIGHT_GRAY = (200, 200, 200)

BROWN = (139, 69, 19)

GREEN = (0, 255, 0)

YELLOW = (255, 255, 0)

5
# Gravity values (in m/s^2)

GRAVITY_VALUES = {

"Earth": 9.8,

"Mars": 3.71,

"Moon": 1.625,

"Jupiter": 24.79,

"Pluto": 0.62,

# Pendulum parameters

pivot = (WIDTH // 2, HEIGHT // 4) # Fixed point

length = 200 # Length of the pendulum rope

angle = 0 # Initial angle (at rest position)

angular_velocity = 0 # Initial angular velocity

angular_acceleration = 0 # Initial angular acceleration

gravity = GRAVITY_VALUES["Earth"] # Default gravity (Earth)

# Timer

start_time = None

6
elapsed_time = 0

timer_active = False

# Swing times

swing_times = []

best_swing_time = None

# Damping factor

damping = 0.99

# Mouse interaction variables

dragging = False

# Clock for controlling the frame rate

clock = pygame.time.Clock()

FPS = 60

# Fonts

font = pygame.font.Font(None, 36)

7
large_font = pygame.font.Font(None, 48)

# Gradient background

def draw_gradient_background():

for y in range(HEIGHT):

# Ensure the color values are within the valid range

red = max(0, min(255, 135 - y // 5))

green = max(0, min(255, 206 - y // 10))

blue = max(0, min(255, 235 - y // 15))

color = (red, green, blue)

pygame.draw.line(screen, color, (0, y), (WIDTH, y))

# Draw the planet selection buttons

def draw_planet_buttons():

button_width = 120

button_height = 50

planets = list(GRAVITY_VALUES.keys())

for i, planet in enumerate(planets):

8
x = 20

y = 50 + i * (button_height + 10)

pygame.draw.rect(screen, LIGHT_GRAY, (x, y, button_width, button_height),


border_radius=5)

text = font.render(planet, True, BLACK)

screen.blit(text, (x + (button_width - text.get_width()) // 2, y + (button_height -


text.get_height()) // 2))

return planets

# Draw the reset button

def draw_reset_button():

button_width = 120

button_height = 50

x = 20

y = HEIGHT - 70

pygame.draw.rect(screen, GREEN, (x, y, button_width, button_height), border_radius=5)

text = font.render("Reset", True, BLACK)

screen.blit(text, (x + (button_width - text.get_width()) // 2, y + (button_height -


text.get_height()) // 2))

9
# Draw the swing times table

def draw_swing_times_table():

table_x = WIDTH - 300

table_y = 20

pygame.draw.rect(screen, LIGHT_GRAY, (table_x, table_y, 280, 200))

pygame.draw.rect(screen, BLACK, (table_x, table_y, 280, 200), 2) # Table border

# Table header

header_text = font.render("Swing Times (s)", True, BLACK)

screen.blit(header_text, (table_x + 20, table_y + 10))

# Draw the rows of recorded swing times

for i, recorded_time in enumerate(swing_times[-5:]):

time_text = font.render(f"{i + 1}. {recorded_time:.2f}", True, BLACK)

screen.blit(time_text, (table_x + 20, table_y + 40 + i * 30))

# Highlight best swing time

if best_swing_time:

10
best_text = font.render(f"Best: {best_swing_time:.2f}s", True, RED)

screen.blit(best_text, (table_x + 20, table_y + 160))

# Draw the wooden rod

def draw_wooden_rod():

rod_length = 60

rod_width = 10

rod_top_left = (pivot[0] - rod_length // 2, pivot[1] - rod_width // 2)

pygame.draw.rect(screen, BROWN, pygame.Rect(rod_top_left, (rod_length, rod_width)))

# Main loop

running = True

while running:

screen.fill(WHITE)

draw_gradient_background()

planets = draw_planet_buttons()

draw_reset_button()

draw_swing_times_table()

draw_wooden_rod()

11
for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

if event.type == pygame.MOUSEBUTTONDOWN:

mouse_x, mouse_y = pygame.mouse.get_pos()

# Check if a planet button is clicked

for i, planet in enumerate(planets):

x = 20

y = 50 + i * (50 + 10)

if x <= mouse_x <= x + 120 and y <= mouse_y <= y + 50:

gravity = GRAVITY_VALUES[planet]

print(f"Selected {planet}, gravity: {gravity} m/s^2")

# Check if reset button is clicked

reset_x = 20

reset_y = HEIGHT - 70

12
if reset_x <= mouse_x <= reset_x + 120 and reset_y <= mouse_y <= reset_y + 50:

# Reset pendulum to initial state

angle = 0

angular_velocity = 0

start_time = None

elapsed_time = 0

timer_active = False

swing_times.clear()

best_swing_time = None

# Start dragging the pendulum with the mouse

pendulum_x = pivot[0] + length * math.sin(angle)

pendulum_y = pivot[1] + length * math.cos(angle)

if math.hypot(mouse_x - pendulum_x, mouse_y - pendulum_y) < 20:

dragging = True

angular_velocity = 0

if event.type == pygame.MOUSEBUTTONUP and dragging:

dragging = False

13
start_time = time.time()

timer_active = True

# Drag the pendulum with the mouse

if dragging:

mouse_x, mouse_y = pygame.mouse.get_pos()

dx = mouse_x - pivot[0]

dy = mouse_y - pivot[1]

angle = math.atan2(dx, dy)

# Simulate pendulum motion if not dragging

if not dragging:

angular_acceleration = -(gravity / length) * math.sin(angle)

angular_velocity += angular_acceleration

angle += angular_velocity

angular_velocity *= damping

# Stop timer when pendulum is fully at rest

if timer_active and abs(angular_velocity) < 0.001 and abs(angle) < 0.01:

14
elapsed_time = time.time() - start_time

swing_times.append(elapsed_time)

if best_swing_time is None or elapsed_time > best_swing_time:

best_swing_time = elapsed_time

timer_active = False

# Calculate pendulum position

x = pivot[0] + length * math.sin(angle)

y = pivot[1] + length * math.cos(angle)

pendulum_pos = (int(x), int(y))

# Draw pendulum shadow

shadow_x = pendulum_pos[0]

shadow_y = HEIGHT - 50

pygame.draw.ellipse(screen, LIGHT_GRAY, (shadow_x - 20, shadow_y - 5, 40, 10))

# Draw pendulum rope

pygame.draw.line(screen, DARK_GRAY, pivot, pendulum_pos, 3)

15
# Draw pendulum bob with 3D effect

pygame.draw.circle(screen, BLACK, pendulum_pos, 20)

pygame.draw.circle(screen, RED, pendulum_pos, 18)

pygame.draw.circle(screen, LIGHT_GRAY, (pendulum_pos[0] - 5, pendulum_pos[1] - 5), 8)

# Display timer

if start_time is not None:

current_time = elapsed_time if not timer_active else time.time() - start_time

timer_text = f"Time: {current_time:.2f} seconds"

text_surface = font.render(timer_text, True, BLACK)

screen.blit(text_surface, (WIDTH // 2 - text_surface.get_width() // 2, HEIGHT - 50))

pygame.display.flip()

clock.tick(FPS)

pygame.quit()

6.2 Modeling
import numpy as np
import matplotlib.pyplot as plt

16
# Constants
gravity_values = {
"Earth": 9.8,
"Mars": 3.71,
"Moon": 1.625,
"Jupiter": 24.79,
"Pluto": 0.62,
}
length = 2.0 # Length of the pendulum (in meters)
theta_0 = 0.2 # Initial angle (in radians)
time = np.linspace(0, 10, 1000) # Time array (0 to 10 seconds)

def pendulum_motion(g, L, theta_0, time):

# Angular velocity
theta_dot = -theta_0 * np.sqrt(g / L) * np.sin(np.sqrt(g / L) * time)
# Angular acceleration
theta_ddot = -theta_0 * (g / L) * np.cos(np.sqrt(g / L) * time)
return theta, theta_dot, theta_ddot

# Plot results for each planet


for planet, g in gravity_values.items():
theta, theta_dot, theta_ddot = pendulum_motion(g, length, theta_0, time)

plt.figure(figsize=(15, 12))

# Angular Velocity
plt.subplot(3, 1, 2)
plt.plot(time, theta_dot, label=f"{planet}: dθ/dt", color="orange")

17
plt.title(f"{planet}: Angular Velocity (dθ/dt)", fontsize=14)
plt.xlabel("Time (s)", fontsize=12)
plt.ylabel("dθ/dt (radians/s)", fontsize=12)
plt.grid(True)
plt.legend()

# Angular Acceleration
plt.subplot(3, 1, 3)
plt.plot(time, theta_ddot, label=f"{planet}: d²θ/dt²", color="red")
plt.title(f"{planet}: Angular Acceleration (d²θ/dt²)", fontsize=14)
plt.xlabel("Time (s)", fontsize=12)
plt.ylabel("d²θ/dt² (radians/s²)", fontsize=12)
plt.grid(True)
plt.legend()

plt.tight_layout()
plt.show()
6.3 Key Functionalities in Code

1. User Interaction:
o Mouse events to drag the pendulum and interact with buttons.
2. Simulation Logic:
o Pendulum motion simulated using angular acceleration and damping factors.
3. UI Elements:
o Gradient background, planet buttons, swing time table, reset button, and a 3D
pendulum effect.

7. RESULTS
7.1 Observations:

1. Swing times vary based on gravitational constants. For example:


o Earth (9.8 m/s²): 3.45 seconds.

18
o Moon (1.625 m/s²): 8.27 seconds.
o Jupiter (24.79 m/s²): 1.95 seconds.
2. Damping results in realistic motion, with the pendulum coming to rest after a few
oscillations.

7.2 Sample Output:

Planet Gravity (m/s²) Swing Time (s)

Earth 9.8 3.45

Moon 1.625 8.27

Jupiter 24.79 1.95

7.3 Graphs
 EARTH

19
20
 JUPITER:

21
 MARS:

22
 MOON:

23
 PLUTO:

 Plots Generated:

Angular Velocity vs. Time

Angular Acceleration vs. Time

Separate plots are generated for each planet to compare how gravity affects motion.

24
7.4 Derivation:
𝐑𝐞𝐬𝐭𝐨𝐫𝐢𝐧𝐠 = −𝐦𝐠𝐬𝐢𝐧(𝛉)

Here:

 m = mass of the pendulum bob,


 g = acceleration due to gravity,
 sin(θ) = component of gravitational force perpendicular to the pendulum.

The torque τ about the pivot is:

τ = −mgLsin(θ)

Using Newton's second law for rotational motion:

τ = Iα

where:

 I = 𝑚𝐿2 (moment of inertia for a point mass at a distance L from the pivot)
𝑑2 θ
 𝑎= (angular acceleration)
𝑑𝑡 2

Equating the two expressions for torque:

𝑑2θ
−mgLsin(θ) = m𝐿2
𝑑𝑡 2

Simplify by dividing through by mL:

𝑑2θ 𝑔
+ sin(θ) = 0
𝑑𝑡 2 𝐿

This is the nonlinear differential equation for the pendulum. For small angles(θ ≈ sin(θ))
which simplifies to:

𝑑2θ 𝑔
+ (θ) = 0
𝑑𝑡 2 𝐿

25
This is a second-order linear differential equation representing simple harmonic motion.

1. For Angular Displacement (𝛉(𝐭)):

The general solution of the equation:

𝑑2θ 𝑔
+ (θ) = 0
𝑑𝑡 2 𝑙

is:

θ(t) = θ0 cos(ωt)

𝒈
𝛉(𝐭) = 𝛉𝟎 𝐜𝐨𝐬(√ 𝐭)
𝑳

where:

 θ0 = initial angular displacement


𝑔
 ω = √ 𝑙 = angular frequency.

𝐝𝛉
2. For Angular Velocity first Derivative ( 𝐝𝐭 ):

The angular velocity is the first time derivative of (θ(t)):


26
𝑑θ d
= [θ0 cos(ωt)]
𝑑𝑡 dt

Using the chain rule:

𝑑θ
= −θ0 sin(ωt)
𝑑𝑡

𝑔
Substituting ω = √ 𝑙 :

𝒅𝛉 𝒈 𝒈
= −𝛉𝟎 √ 𝐬𝐢 𝐧 (√ 𝒕)
𝒅𝒕 𝑳 𝑳

𝐝𝟐 𝛉
3. For Angular Acceleration Second Derivative ( 𝐝𝒕𝟐 ):

The angular acceleration is the second time derivative of (θ(t)):

d2 θ d
= [−θ0 ωsin(ωt)]
d𝑡 2 dt

Using the chain rule again:

d2 θ
= −θ0 ω. ωcos(ωt)
d𝑡 2

Simplify:

d2 θ
= −θ0 ω2 cos(ωt)
d𝑡 2

27
𝑔
Substituting ω2 = ∶
𝐿

𝐝𝟐 𝛉 𝒈 𝒈
𝟐
= −𝛉𝟎 𝐜𝐨𝐬(√ 𝒕)
𝐝𝒕 𝑳 𝑳

Summary of Results:

For a pendulum with length 𝐿 under gravity 𝑔

1. For Angular Displacement (𝛉(𝐭)):

𝒈
𝛉(𝐭) = 𝛉𝟎 𝐜𝐨𝐬(√ 𝐭)
𝑳

𝐝𝛉
2. For Angular Velocity ( ):
𝐝𝐭

𝒅𝛉 𝒈 𝒈
= −𝛉𝟎 √ 𝐬𝐢𝐧(√ 𝒕)
𝒅𝒕 𝑳 𝑳

𝐝𝟐 𝛉
3. For Angular Acceleration ( 𝐝𝒕𝟐 ):

𝐝𝟐 𝛉 𝒈 𝒈
𝟐
= −𝛉𝟎 𝐜𝐨𝐬(√ 𝒕)
𝐝𝒕 𝑳 𝑳

28
8. DISCUSSION

1. Effectiveness:
o The simulation effectively visualizes the impact of gravity and damping on
pendulum motion.
o Real-time interaction adds significant educational value.
2. Limitations:
o The simulation is dependent on pygame, which might not perform optimally on
low-end systems.
o Swing times are calculated with some variation due to frame rate dependencies.
3. Potential Improvements:
o Add more planets or allow users to input custom gravitational constants.
o Incorporate friction or air resistance into the simulation.

9. CONCLUSION

The Interactive Pendulum Simulation is a dynamic educational tool designed to demonstrate the
interplay of gravity, damping, and angular motion in the behavior of a pendulum. By combining
theoretical physics principles with real-time visualization, it offers a hands-on learning experience
that simplifies complex ideas for students and educators. Gravity, as the driving force, is visibly
shown pulling the pendulum toward its equilibrium position, while damping illustrates the gradual
energy loss over time due to resistance or friction, ultimately slowing the motion. Angular motion,
influenced by factors like the initial displacement or angle, showcases how the pendulum's
oscillation changes in response to these variables.

The simulation allows users to manipulate key parameters, such as the pendulum's length, mass,
initial angle, or damping factor, and observe how these adjustments influence its motion. For
example, increasing the length of the pendulum slows its oscillation, while adding damping
reduces the amplitude over time, mimicking real-world scenarios like air resistance. This
interactive experimentation bridges the gap between abstract theoretical concepts and practical
application, helping learners build an intuitive understanding of physics.

Beyond its scientific accuracy, the simulation engages learners by making physics both accessible
and enjoyable. It fosters curiosity by encouraging exploration and experimentation, catering to
diverse learning styles and promoting active problem-solving. Educators can use this tool to

29
visually demonstrate concepts that are often challenging to convey through static diagrams or
equations alone, while students gain the opportunity to test hypotheses and witness immediate
results. Ultimately, the Interactive Pendulum Simulation serves as a versatile and engaging
resource, enabling a deeper appreciation for the fundamental principles of motion and dynamics
in physics.

10. REFERENCES
 Hughes, S., & Young, M., 2024, May. Planets, spring, and pendulum. In Physics Education
(Vol. 59, No. 4). IOP Publishing.
Link: https://iopscience.iop.org/article/10.1088/1361-6552/ad48f1
 Jonathan Horner, Pam Vervoort, Stephen R. Kane, Alma Y. Ceja, David Waltham, James
Gilmore, and Sandra Kirtland Turner Quantifying the Influence of Jupiter on the Earth's
Orbital Cycles. Published 2019 December 12 • © 2019. The American Astronomical Society.
All rights reserved.The Astronomical Journal, Volume 159, Number 1
Link: https://iopscience.iop.org/article/10.3847/1538-3881/ab5365

30

You might also like