Skip to content

Instantly share code, notes, and snippets.

@Nil-Zil Nil-Zil/leap_frog.py
Created Jan 19, 2018

Embed
What would you like to do?
#!/usr/bin/env python
# created at Jan 18, 2017 22:06 by Nil-Zil
"""
Leap frog algorithm.
"""
import matplotlib.pyplot as plt
import numpy as np
time = 10
niter = 500 # number of iterations
t = np.linspace(0, time, num=niter, endpoint=True)
class LeapFrog(object):
def __init__(self, time, niter):
self.position = []
self.velocity = []
self.vel = 0 # intermediate variable
self.pos = 1 # intermediate variable
self.force = 0 # intermediate variable
self.time = time
self.niter = niter
self.time_step = self.time / self.niter
self.mass = 1
self.k = 1 # stiffness coefficient
def iter(self):
for i in range(niter):
# step 1 of leap frog
self.vel += self.time_step / 2.0 * self.force / self.mass
self.pos += self.time_step * self.vel
# step 2 of leap frog
self.force = - self.k * self.pos
self.vel += self.time_step / 2.0 * self.force / self.mass
self.velocity.append(self.vel) # record vel after 1 time step
self.position.append(self.pos) # record pos after 1 time step
def spectra(self):
return np.fft.fft(self.velocity)
def omega(self):
return np.fft.fftfreq(self.niter, d=self.time_step) * 2 * np.pi
leap = LeapFrog(time, niter)
leap.iter()
plt.figure()
plt.plot(t, leap.position)
plt.plot(t, leap.velocity)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.