How To Wiki

Howto compare floating point numbers in the C programming language

1,795pages on
this wiki
Add New Page
Talk2 Share

Description Edit

It is very usual for the C programming language beginners to compare a floating point number using the "==" operator. Floating point numbers must not be compared with the "==" operator.

That is mainly because when you compute a float number you will get a result like 1.543645274878272 and if you compare 1.543645274878272 with 1.5436, the result will always be false.

1.543645274878272 != 1.5436

Solution using a function Edit

Instead of comparing float numbers with the "==" operator, you can use a function like this one.

 //compares if the float f1 is equal with f2 and returns 1 if true and 0 if false
 int compare_float(float f1, float f2)
  float precision = 0.00001;
  if (((f1 - precision) < f2) && 
      ((f1 + precision) > f2))
    return 1;
    return 0;

// or

bool fequal(float a, float b)
 return fabs(a-b) < epsilon;

You can set the precision of the comparison between the floating point numbers by changing the "precision" variable.

==== Usage of the solution ====
To use the solution above for comparing the floating point number 11 and the floating point number x2, you can do :
 //we compare our numbers
 if (compare_float(x1,x2))
   //do something if equal

See also Edit

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Also on Fandom

Random Wiki