I would like some advise on how to optimise the following while loop:
double minor_interval = 0.1;
double major_interval = 1.0;
double start = 0.0;
double finish = 10.0;
printf("Start\r\n");
while (start < finish)
{
printf("Minor interval: %.20f\r\n", start);
double m = fmod(start, major_interval);
printf("m: %.20f\r\n", m);
if (m == 0)
printf("At major interval: %.20f\r\n", start);
start += minor_interval;
}
printf("Finished\r\n");
Essentially, I am incrementing a counter in the loop by the minor interval and would like to know every time around the loop if I am at a major interval. Picture this as drawing a ruler with millimeter intervals, and every time I get to a major interval, I want to draw a centimetre. Given inaccuracies in floating point arithmetic, how can I modify the above loop to implement the functionality I require? I have tried different methods of comparing the result of the modulus using a tolerance with no luck. Note that the minor and major intervals can be any values i.e. minor = 0.4 and major = 1.6 (to draw quarter mile increments).
Thanks in advance.
I would implement this with a for loop over an
intvariablei. Using integers avoids rounding problems due to the limitations of floating point arithmetic. [See What Every Computer Scientist Should Know About Floating-Point Arithmetic.]Let
irun from0toiFinish-1and settimeequal tostart + i*minor_interval. The value ofiFinishcan be found by rounding(finish-start)/minor_intervalto the nearest int.Major axis updates can be handled in a similar way. Round
major_interval/minor_intervalto the nearestint, sayk. Then update major axis marks every k-th iteration.In terms of code it looks like this: