# B Numerical integration of an harmonic oscillator using java

1. Aug 9, 2016

### user123897

Hi, im 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?

2. Aug 9, 2016

### BvU

what's this ?

3. Aug 9, 2016

### user123897

average acceleration. note that the a in the right side is the previous acceleration.

4. Aug 9, 2016

### QuantumQuest

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?

5. Aug 10, 2016

### BvU

I see. It's not he problem, though. In fact I can't reproduce your runaway:

6. Aug 10, 2016

### user123897

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

7. Aug 10, 2016

### BvU

10 milliseconds isn't bad. 10 seconds is.

8. Aug 11, 2016

### vanhees71

The main problem is using Java for numerics, I guess ;-)). SCNR.

9. Aug 11, 2016

### BvU

Real programmers can write Fortran in any language.