Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Float Type

Status
Not open for further replies.

crmayer

Programmer
Nov 22, 2002
280
US
I am trying to compare to numbers of type float and it keeps returning that they are not the same. So I printed them to the screen right before they are compared and I am getting this:


216.9000008 = 216.9000000

All I care about is 216.90, how can I just compare the up to 2 digits past the decimal point?
 
Comparing floats is notoriously prone to failure. A classic case is:-

Code:
float i = 1.0;
i /= 3.0;
i *= 3.0;
if ( i == 1.0 ) //  fails, i = 0.9999999999 (or who knows exactly)

Comparisons shoud really only be done on ints, chars etc.

If you only need to compare to two decimal places, mutiply by 100, convert to int and compare the results.

 
You can do this:

/* Assume floatnum is 216.908 and floatconstant is 216.9005 */

/* 21690 == 21690 */
if( (int)(floatnum*100) == (int)(floatconstant*100))
{
/* They're equal */
}
else
{
/* They aren't equal */
}

Multiply by powers of 10 past the decimal to adjust your precision, 10 for 1 place, 100 for 2 places, 1000 for 3, and so forth.
 
Code:
if (fabs(x-y) > 0.01) // x != y...
It's rather dangerous method: you may get overflow (or underflow on some processors), but c'est la ... floating point arithmetics.
The only safe comparison on equality with floats is:
Code:
if (x == 0.0) ...
// or
if (x != 0.0) ...
In practice a safe method must be in that style:
Code:
if (fabs(x-y) < eps) // then x == y
One more advice: never use float in calculations, use double only. 32-bit floats have too low precision.
Remember that:
1. Floating point numbers are NOT math real numbers.
2. They are approximated values only.
3. Decimal fractions are not equal to its math values on binary computers.
4. It's possible and is not (formally) error:
Code:
Input file line:
0.1
...
double x = 0.1;
double y;
scanf("%lf",&y); 
/* compiler and RTL may use slightly different cvt rules */
if (x == y)
{
  /* You may never come here!..
}
else
{
  /* Yes, x != y, but it's logical (and design) error...
}
It's so crafty thing - floating point...
 
LOL Salem...
Le centre charles Hermite :)

How do you know them?
 
Status
Not open for further replies.

Similar threads

Replies
3
Views
97
  • Locked
  • Question
Replies
4
Views
111
Replies
3
Views
181

Part and Inventory Search

Sponsor

Back
Top