In the main program, I want to print out the value of t and the kinetic energy every 10*step only but it never prints. I found out the reason of this is because t never equals 10*step: t is initialized to 0 at the beginning and add 0.01(which is dt) in each iteration and it does the calculation correctly until it reaches t=0.83. In this iteration, 0.01 is added to t gives 0.839999 which mess up the calculation. Can somebody tell me how to fix it and why it happens?? Thanks!
The bottom line is that you can't compare floating point values using ==. You need to test whether the value is within a small range of the number you want to compare against, i.e. if (abs(t-10*step)<epsilon)...
Doubles are obviously more accurate, but they still suffer from the same issues; you can not trust comparison operations to function as they would for integers. This has to do with the fact that most floating point values are not exact, they are an approximation unless they happen to be something that comes out evenly in base 2 and fit within the precision of the value. Just like 1/3 is infinitely repeating in decimal (0.33333...), most real numbers do not come out evenly in base 2. So 1/10 comes out evenly in base 10 as 0.1, but not in base 2. Fractions that would be non-repeating in base 2 are those with powers of 2 in the denominator; 1/2, 1/4, 1/8, 1/16, etc.