Array indexing vs. pointers...

Andrew Koenig ark at alice.UUCP
Sat Oct 8 23:51:47 AEST 1988


In article <1706 at dataio.Data-IO.COM>, bright at Data-IO.COM (Walter Bright) writes:
> 	For example, suppose you wished to convert Celsius to Farenheit
> 	in a tight loop. Multiplying by the scale factor is much faster
> 	than dividing by the reciprocal, and the answer will be correct
> 	to the desired accuracy.

This obviously depends on what you desire.  For instance,
whether I evaluate

	f = 32 + c * (9.0/5.0);

or

	f = 32 + c / (5.0/9.0);

I will not get as accurate an answer as if I evaluate

	f = 32 + (c * 9.0) / 5.0;

Now, I know that a sensible compiler will do the division inside
the parentheses for me at compile time in each of the first two
examples above, where the third one does a multiplication *and*
a division.  The third is clearly the slowest.  But on a machine
with sensible floating-point, it guarantees me the most accurate
result possible whenever c is an integer.  In particular, when
I convert 100 degrees Celsius to Fahrenheit, I get 212, not
211.9999999999999 or 212.0000000000001.  The other two ways of
doing it do not guarantee that.
-- 
				--Andrew Koenig
				  ark at europa.att.com



More information about the Comp.lang.c mailing list