You must be very careful when iterating with float counters. As an example, I will show you what happens in your case (this is a Java program, but your case should be the same): click here to start it yourself
double h = 0.1; System.out.println(10*h-1.0); System.out.println(h+h+h+h+h+h+h+h+h+h-1.0);
It simply prints the difference in unit when doing the additions of multiplication and sampling.
Since the float representation is not accurate, the result is as follows:
0.0 -1.1102230246251565E-16
Thus, if you use this as a loop condition in the latter case, there will be an additional iteration (not yet achieved).
Try using the counter variable i
, which is an integer, and you will not run into such problems.
source share