Howto compare floating point numbers in the C programming language

Description
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
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; } else {   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 } else { }