Euler Method Harmonic Oscillator I have written very simple Python code to solve the simple harmonic oscillator using Euler method, but I am not sure if the program is correct or not. I would be very grateful if anyone can look at my code and suggest further improvements since I am very new to this programming thing.

import matplotlib.pyplot as plt
v=0.0   #initial velocity
h=0.01  #time step
x=5.0   #initial position

t=0.0
ta,xa=[],[]

while t&lt;1.0:
    ta.append(t)
    xa.append(x)

    v=v-(10.0/1.0)*x*h    #k=10.0, m=1.0
    x=x+v*h
    t=t+h
plt.figure()
plt.plot(ta,xa,'--')
plt.xlabel('$t(s)$')
plt.ylabel('$x(m)$')
plt.show()
The code is quite monolithic: calculation and presentation are separate concerns, and while I appreciate the context given by showing the presentation, it would be better to make clear that they're separate concerns by separating them with whitespace and commenting briefly.

Also on structure: separate constants (h) from variables (v, x, t).




    v=v-(10.0/1.0)*x*h    #k=10.0, m=1.0
    x=x+v*h
    t=t+h



Two things: firstly, what are k and m? It seems that they should be constants with comments explaining their physical significance.

Secondly, this isn't Euler's method. Euler's method is \$\vec{x}_{n+1} = \vec{x}_n + hf(t_n, \vec{x}_n)\$ where \$f = \frac{d\vec{x}}{dt}\$. Here \$\vec{x} = (v, x)\$ and \$f(t, v, x) = (\frac{dv}{dt}, \frac{dx}{dt}) = (-\frac{k}{m}x, v)\$. In other words, to be Euler's method you should update x according to the previous value of v, not the updated value of v. Since you're using Python, you can take advantage of simultaneous assignment:

    v,x=v-(k/m)*x*h,x+v*h
    t=t+h


(As it happens your buggy implementation works better than Euler's method, but if it was intended to implement Euler's method then it's still technically buggy).