I am trying to model a dynamical system in C++ and have some issues with the precision of stored values.
I have read the question on the floating point precision, but am unable to figure out what is going wrong in my case.
So, the issue is about storing the particle velocity. For example, the particle starts with velocity 1.01 and because of the nature of dynamical system it can only gain or lose 0.4 units at each interaction.
The value of velocity is stored okay (correct to full precision) for the first 2890 interactions. At the 2891st interaction, the velocity becomes
4.209999999999999
instead of
4.21
Does this happen because at that point the velocity reaches an "ugly" value for the first time? After 2890 interactions though?
I have two possible fixes of this problem in mind and would like to ask you for advice. Please keep in mind that I need to vary initial velocity, not just use 1.01.
Change the units of the system so that it gains or loses 1.0 velocity at each interaction. (Will this even work? For example, if the starting velocity is 1.21, it would probably get the same error at the 4.21 value?)
Round the velocity to some fixed number of decimal places after each interaction. (I don't like this very much, because I would have to know the precision of the velocity in advance, which would make the program clumsier)
Thank you for possible thoughts on this.