[comp.lang.c] Zero comparisons

christiansen@chewi.che.wisc.EDU (REED CHRISTIANSEN) (03/23/88)

>> >
>> >This is of course wrong.  Floating-point imprecision is not due
>> >simply to float<->double conversion, but is inherent in the
>> >whole approach.
>> 
>> Yup.  Interestingly, this is one of the very first things I can remember
>> being taught in "computer science" - NEVER test "reals" against absolute
>> values - choose a precision and test against values +/- that precision.
>
>One of the "tricks" I do when optimizing code is handling typical cases
>different from the general case.  In particular, I do alot with
>3-d geomety and 3-d rotations.  The typical transform case has zero roll and
>pitch angular rotations (x and y axis rotations).  Its to my benefit
>to test for this situation and handle it differently.  The test
>I use is a direct equality test to see if the roll and pitch angles
>are zero and if so only perform a rotation about the z-axis.

Zero equality tests on input data are not a problem; the bothersome
situation is testing for zero as a result of a computation.  When I
learned my numerical analysis (FORTRAN), I was taught that the
portable method of testing whether some result is "nearly" zero is:

	if (RESULT+1. == 1.)
	{
		do code for ``result == 0''
	}

("Nice" packages like LINPACK do this).  The rationale, of course, is that
the sum RESULT+1. forces a normalization with respect to unity that is
analogous to any other normalization that might occur in your code. Thus,
one does not need to worry whether the compiler generates intermediate
stores to memory in your code--it remains bullet proof.  And, one doesn't
have to come up with a shopping list of epsilons when one ports to a new
environment.

I haven't had any problem using the same construct in C with
Datalight C or VMS C, but I'm wondering whether there are any optimizing
compilers out there that will "optimize out" the ones in the IF
statement ( i.e., (RESULT+1. == 1.) ----> (RESULT == 0.) )

Thanks,                          | Small Song
                                 | ===== ====
Reed L. Christiansen             | The reeds
UW Dept of Chemical Engineering  | give way to the
1415 Johnson Drive               |
Madison, WI  53706               | wind and give
(608)262-7267                    | the wind away  -- A.R.Ammons, 1970

Internet: CHRISTIANSEN@CHEWI.CHE.WISC.EDU
------