C Floating point arithmetic

Jonathan P. Leech jon at cit-vax.arpa
Sat Dec 7 20:10:57 AEST 1985


>>>	 float a,b;
>>>
>>>	 a = b + 1.0;	 /* Gets done in double because 1.0 is a double.
>>>			 Gag me with a spoon. */
>>
>>Nah, gets done in single because the compiler realizes that 1.0 has
>>the same representation in single and double, and therefore that
>>the result of the addition will be the same.
>
>The point is that most floating-point constants are very simple: 1.0,
>0.0, sometimes 2.0.  It doesn't take much to recognize such constants
>and do the operations in single.  This is true even if your compiler isn't
>up to it.
>

    There are potential pitfalls here also. For example, last summer I
was involved in a project to attempt to ray-trace arbitrarily deformed
parametric patches. The computation of the deformations  involved  the
constant PI  =	3.1415...  For	some  strange  reason,	the  numerical
technique we were using took 10 times as long to converge as it should
have. After several days of  head-bashing,  it	turned	out  that  the
FORTRAN compiler we were using interpreted PI as  a  single  precision
constant, and that loss of accuracy was sufficient. (Perhaps  this  is
standard FORTRAN behavior - I don't know as I am mainly a C hacker)

    It makes  a  great	deal  more  sense  to  me  to  have  constants
double-precision by default. If you're really sure you	can  get  away
with single precision, fine, but don't assume it as default behavior.

    -- Jon Leech (jon at cit-vax.arpa)
    __@/



More information about the Comp.lang.c mailing list