Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I program a pendulum effect in Python?

Tags:

python

pygame

I'm working on making a game in Python (teaching myself Python in the process) and I'm trying to add a pendulum function, but I've never programmed a pendulum function before or even seen code that successfully creates a pendulum. So I'm hoping you guys can help me out here. How exactly do I create a pendulum function in Python?

like image 202
IronGiraffe Avatar asked Dec 01 '25 16:12

IronGiraffe


1 Answers

I suppose you need an algorithm (since you say that you want to create a pendulum function). After searching a little bit, i found something that may work for you :

#!/usr/bin/env python

def pendulum(T, n, theta0, v0, alpha):
    """Return the motion (theta, v, t) of a pendulum."""
    dt = T/float(n)
    t = linspace(0, T, n+1)
    v = zeros(n+1)
    theta = zeros(n+1)
    v[0] = v0
    theta[0] = theta0
    for k in range(n):
        theta[k+1] = theta[k] + dt*v[k]
        v[k+1] = v[k] - alpha*dt*sin(theta[k+1])
    return theta, v, t

from scitools.std import *
try:
    n = int(sys.argv[1])
    T = eval(sys.argv[2])
    v0 = eval(sys.argv[3])
    theta0 = eval(sys.argv[4])
    alpha = eval(sys.argv[5])
except:
    print "usage:", sys.argv[0], "n T v0 theta0 alpha"
    sys.exit(1)

theta, v, t = pendulum(T, n, theta0, v0)
plot(t, v, xlabel='t', ylabel='velocity')
figure()
plot(t, theta, xlabel='t', ylabel='velocity')

source : vefur.simula.no/intro-programming/src/ode/pendulum.py

like image 115
Spyros Avatar answered Dec 04 '25 05:12

Spyros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!