## Wednesday, April 7, 2010

### Comparing floats

Problem
int main()
{

float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}

Output - I hate U
Explanation
For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value represented varies. Float takes 4 bytes & long double takes 10 bytes. So float stores 0.9 with less precision than long double.

Solutions
`//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;   } }You can set the precision of the comparison between the `
`floating point numbers by changing the "precision" variable.`
`Calling the function: //we compare our numbers if (compare_float(x1,x2)) {   //do something if equal } else {   //do something if not equal }`

Method2 - using fabs i.e.  epsilon absolute error
if (fabs(me - you) < 0.00001)
printf("I love U");
else
printf("I hate U");

Absolute error calculations have their place, but they aren’t what is most often used. When talking about experimental error it is more common to specify the error as a percentage. Absolute error is used less often because if you know, say, that the error is 1.0 that tells you very little. If the result is one million then an error of 1.0 is great. If the result is 0.1 then an error of 1.0 is terrible.