Reputation: 21
Ive been trying to numerically solve for the graph of a basic harmonic oscillator but a problem occurs when acceleration on the object is proportional to the inverse of the distance from the centre:
import math
from pylab import *
xg = [2]
xt = [0]
k = 1
dt = 1/1000
Vx = 0
for i in range(800000):
a = -1/xg[i-1] #acceleration on the object
Vx = Vx + dt*a
xg.append(xg[i-1]+Vx*dt)
xt.append(i*dt)
plot(xt,xg)
show()
As you can see it seems to dip down and not return for some reason.
I am wondering what is causing this to happen, I've been trying to solve this for hours.
Yes, I am new to python, stack exchange and solving problems numerically. Any feedback is appreciated
Upvotes: 2
Views: 2835
Reputation: 196
Assuming you want an acceleration proportional to the inverse of the distance, the numerical values will diverge when xg is near 0, inducing numerical instability.
Upvotes: 0
Reputation: 3364
Try this instead
import math
from pylab import *
xt = [2]
t = [0]
k = 1
dt = 0.0001
Vx = 0
for i in range(800000):
t.append(dt*i)
a = -k*xt[i]
xt.append(xt[i] + dt*Vx)
Vx = Vx + dt*a
plot(t,xt)
show()
You end up with this: (I also decreased the time step fyi to 1/10000)
Upvotes: 2