Oscillating system with spring and damper.
A differential equation for the system in Figure reads
In the linear damping case, where $f(u')=bu'$ for some constant $b\geq 0$, we can solve the problem numerically by a scheme
for $n=0,1,\ldots$. A special formula is required for $n=0$:
In [1]:
from numpy import zeros
In [2]:
def solver_linear_damping(I, V, m, b, s, F, t):
N = t.size - 1 # No of time intervals
dt = t[1] - t[0] # Time step
u = zeros(N+1) # Result array
u[0] = I
u[1] = u[0] + dt*V + dt**2/(2*m)*(-b*V - s(u[0]) + F[0])
for n in range(1,N):
u[n+1] = 1./(m + b*dt/2)*(2*m*u[n] + \
(b*dt/2 - m)*u[n-1] + dt**2*(F[n] - s(u[n])))
return u
N = t.size - 1 # or len(t) - 1
Creating an array of length $N+1$ where we can store the solution is done by
u = zeros(N+1)
For loops over array indices are coded as
for n in range(1, N):
...
In [3]:
# The solver module is in src/solver.py; tell Python about that
import sys
sys.path.insert(0, 'src')
In [4]:
%matplotlib inline
from solver import solver_linear_damping
from numpy import linspace, zeros, pi
def s(u):
return 2*u
T = 10*pi # simulate for t in [0,T]
dt = 0.2
N = int(round(T/dt))
t = linspace(0, T, N+1)
F = zeros(t.size)
I = 1; V = 0
m = 2; b = 0.2
u = solver_linear_damping(I, V, m, b, s, F, t)
from matplotlib.pyplot import *
plot(t, u)
show()