Evaluating a Num Linearly Spaced Intervals
We are frequently confronted with evaluating a mathematical expression at Num
linearly spaced equidistant intervals.
Consider the following example;
float start_time, end_time, y;
int n, num=100;
... /* start_time and end_time set to values by user */
for(n=0; n<=num; n++)
t = start_time + (end_time - start_time) *n / num; /* ****** */
y = calculation(t); /* evaluate some kind of expression */
printf("%f\t%f\n", y, t);
Note how a simple index is used to painlessly determine num+1 equally spaced
points. In this case, 100 intervals; 101 points.
It is important that you understand the line marked thus /******/.
Also, note that the order is important. In the above, (end_time -
start_time) is a float. Thus, (end_time - start_time) * n is a float (as a
float times an int is a float). Thus, (end_time - start_time) * n / num is a
float and all is well.
The following might look the same, but it isn't and will not work as desired.
t = start_time + n/num* (end_time - start_time);
In this case n/num (an integer divided by an integer) is zero for n=0..99.
Thus, t will always be start_time + 0.0, which isn't too useful.
However, the following will work.
t = start_time + ((float) n)/num* (end_time - start_time);
Note that n is type cast as a float. A float divided by an int is a float.
Again, all is well.