I'm trying to plot the function m*x''(t) + r*x'(t)+k*x(t) = 0
and so after some solving it goes to:
x(t+2h) = x(t+h)*(2-(r*h/m)) + x(t) * (-1 + (r*h/m) - (k*h*h/m))
so i tried making a python script that makes this recursion and then plots the graph but i'm doing sth wrong
import matplotlib.pyplot as plt
m = 0.015
k = 5.0
r = 0.24
h = 0.1
x0 = 0.05
v0 = 0
def displacement(t):
if t <= 0:
return x0
elif t == h:
return v0*h + x0
else:
return displacement(t-h)*(2-((r*h)/m)) + displacement(t-2*h)*(((r*h)/m) - 1 - ((k*h*h)/m))
#xn(2 - s*h/m - k*h^2/m) + xn-1(s*h/m - 1) = xn+1
# x(n - 1) = x(t - h)
#x1' = x1-x0/h => x1 = v0*h + x0
t_values = []
for i in range(50):
t_values.append(i/10)
print(t_values)
xt_values = []
for j in t_values:
xt_values.append(displacement(j))
print(xt_values)
print(xt_values)
#t_values = [t/100000 for t in range(200000)]
#xt_values = [displacement(t) for t in t_values]
plt
plt.plot(t_values, xt_values)
plt.title('Damped Spring System')
plt.xlabel('Time')
plt.ylabel('Displacement(x)')
plt.show()
All things m, k, r, h are parameters as well as the first 2 cases of recursion which are 1 and 0. Is there any coding mistake I'm making or is it just a skill issue in the physics part?
The expected graph is something like a COS graph but the amplitude decreases over time and the period gets larger and larger. The graph I'm getting is a very strange alternating + and - graph that gets bigger and bigger over time almost exponentially (very fast, the computer can't handle samples very quickly.)