Q59316: Evaluating Floating-Point Values to Zero
Article: Q59316
Product(s): See article
Version(s): 5.10 6.00
Operating System(s): MS-DOS
Keyword(s): ENDUSER | s_quickc s_quickasm | mspl13_c
Last Modified: 17-DEC-1990
Comparing small double values to 0 (zero) causes machines with
coprocessors to hang. Since double values use 64 bits (or 8 bytes) to
store their values and a coprocessor uses an 80-bit register to hold
floating point values, there is a 16-bit difference that causes any
operations on the double values to be inaccurate. In Microsoft C
version 6.00 and Quick C version 2.50, the long double type is fully
supported and can be used to exactly match the coprocessor form. In
that case, the problem goes away.
Zero is an absolute value and not always the best value to evaluate
small float values to. The recommended way to evaluate a float value
is to compare the float with a small value other than 0 (for example,
0.00001).
Sample Code
-----------
/* The following sample program demonstrates the problem when
* evaluating a small double value to 0.
*/
#include <stdio.h>
double rz = 0.7;
void main (void)
{
int i = 0;
while (rz != 0.0) {
rz = rz * rz;
i++;
}
printf ("rz = %lf i = %d\n", rz, i);
}
The recommended way is to replace the while() loop in the above code
with the following:
while (rz >= 0.00001) {
rz = rz * rz;
i++;
}
THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.
Copyright Microsoft Corporation 1986-2002.