Numerical integration of an harmonic oscillator using java

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
8 replies · 2K views
user123897
Messages
3
Reaction score
0
Hi, I am trying to analyze the an harmonic oscillator using kinematics.
first i calculate the force applied by the spring (f = (-x)*k)
then i calculate the acceleration (a = f/m)
then speed (v= v0 + v0t + 0.5*a*t^2)
and finally update x (x = x0+vt)

this is a simplfied loop of my program (written in java, all values are initialized to 0 expect x = 10)

{
x = x + v * dt + 0.5 * a * Math.pow(dt, 2);
f = k * (-x);
a = ((f / m) + a) / 2;
v = v + a * dt;
a = f / m;
}

this loop runs evry dt milliseconds.

the values of x,v,a,f increase rapidly and aims to infinitey

can someone understand where i got it wrong?

thanks for your time :)
 
Physics news on Phys.org
BvU said:
what's this ?
average acceleration. note that the a in the right side is the previous acceleration.
 
user123897 said:
can someone understand where i got it wrong?

What kind of loop is this (for, while...) and where are the condition(s) of it, especially the one (or whatever combination), that stop the loop from running indefinitely? From what function do you get dt to count?
 
user123897 said:
average acceleration. note that the a in the right side is the previous acceleration.
I see. It's not he problem, though. In fact I can't reproduce your runaway:

upload_2016-8-10_10-27-5.png
 
BvU said:
I see. It's not he problem, though. In fact I can't reproduce your runaway:

View attachment 104489
Figured out the problem. I dt = 10, way too big considering the expected period time.

Thanks for your help!