Hi all,
One more question about my Euler method problem. The usual Euler method is not energy conserving (it diverges with time), so it has to be modified. If you solve the simple harmonic oscillator with spring constant k and mass m, position and velocity should have this form:
The problem is that I don't get a circle in the (x,v) diagram, I get a spiral which will have increased amplitude and velocity with increasing time. I cannot find any major errors in the code. Somebody has an idea?
When talking about Euler you need to be more precise.
According to your formula, you need the future velocity to calculate the position. But in the code you're using the current one.
Also, integer division returns an integer
I don't think I have to write the derivation of the formulae here. It is sufficient to know that in order to solve the divergence problem one replaces v(t) by v(t+Δt) in the first formula. I think I have covered that by setting aSpring.iVelocity = iV[i] in the code. If I put it like this it looks exactly like in the formula, i.e. the current velocity is replaced by the velocity in the future.
The error for constant Δt is also constant. The divergence comes from the replacement of the the first order derivates by their forward finite differences. All I can say that "everywhere" it is stated that if you replace the t by t+Δt in the first equation you should get a stable solution which obeys energy conservation (of course with the mentioned error squared).
Sure, use backward Euler instead of forward Euler.
But again, your code is forward Euler. When calculating X[K] you are using V[K-1], it should be V[K]
The error for constant Δt is also constant
You can't say that the error is constant. It depends on the step, but also on a derivative of the function evaluated in some point of the interval.
for (int K = 1; K <= aSteps; ++K)
{
V[K] = V[K-1] - X[K-1]*C*Dt;
X[K] = X[K-1] + V[K]*Dt; //as we need the calculated value for V, this need to be after.
}