Java Numerical integration of an harmonic oscillator using java

AI Thread Summary
The discussion revolves around analyzing a harmonic oscillator using kinematics in a Java program. The user outlines their approach, which involves calculating force, acceleration, speed, and updating position in a loop. However, they encounter an issue where the values of position, velocity, acceleration, and force increase rapidly towards infinity. The user questions the average acceleration calculation and the structure of their loop, seeking clarification on the conditions that prevent infinite execution. Other participants note that the problem likely stems from a large time step (dt = 10 milliseconds), which is inappropriate for the system's expected period. The conversation highlights the challenges of numerical stability in Java and suggests that the choice of programming language may affect the results.
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 :)
 
Technology news on Phys.org
user123897 said:
a = ((f / m) + a) / 2;
what's this ?
 
  • Like
Likes vanhees71
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!
 
10 milliseconds isn't bad. 10 seconds is. :smile:
 
The main problem is using Java for numerics, I guess ;-)). SCNR.
 
Real programmers can write Fortran in any language.
 
  • Like
Likes anorlunda and vanhees71

Similar threads

Replies
4
Views
5K
Replies
5
Views
3K
Replies
50
Views
5K
Replies
11
Views
1K
Replies
6
Views
2K
Replies
15
Views
3K
Replies
6
Views
7K
Replies
8
Views
2K
Back
Top