0

i'm having troubles in comparing a double value to a value such as "5.5". in my code i have the following:

if (j==5.5f) {
        //do something
    }

when i run the code and use nslog to print the values of the value of j and 5.5f i get the exact same values. However, the code doesn't enter the if statement. what is wrong here?

HusseinB
  • 1,321
  • 1
  • 17
  • 41
  • 1
    http://floating-point-gui.de –  Sep 02 '13 at 16:24
  • 1
    Not sure but try use NSnumber instead. `NSNumber *num = [NSNumber numberWithFloat:5.5f]; //j if ([num isEqualToNumber:otherNum]) { // do something }` – BooRanger Sep 02 '13 at 16:24
  • 1
    First you *must* define what you mean by a "decimal number". The only "decimal" supported by Objective-C is NSDecimalNumber. If you simply mean a number, which may be represented in decimal when displayed, you must define whether it's an integer or float value. If it's a float value, you must be wary of the fact that floating-pont numbers are not generally exact, so comparing with `==` is usually a bad idea. – Hot Licks Sep 02 '13 at 16:32

3 Answers3

2

1) first double is different than float so for the constant you should remove the 'f' in the constant, so use: 5.5 instead of 5.5f (constants are double by default)

2) because floating point numbers do not have an exact representation, in order to compare two of them you have to use a threshold

So replace the conditional with:

#include <math.h>

static double threshold = 1e-10
if (fabs(j-5.5) < threshold) { // dont use the f for the literal 
}
Juan Catalan
  • 2,299
  • 1
  • 17
  • 23
1

This is probably a floating point precision issue. In general, since floating point values are often not exact representations, you need to compare a range, such as:

if (abs (j - 5.5) < epsilon)
{
    ... do your work....
}

This says that if j is within epsilon of 5.5, then do something. The value of epsilon will be application-depenendent.

user1118321
  • 25,567
  • 4
  • 55
  • 86
0

The implementation of floating point numbers poses a very common problem of precision when tried to be compared, as they are not implemented as normal integers. The difference between two floats that seem to be equal can be very very small and you therefore need to define some sort of threshold or epsilon value as already stated, that you must use when comparing two floating point numbers.

It is a very good code practice to never compare floats or doubles with a '==' equation, and always use a threshold value as already shown or a built-in function for the purpose, no matter platform, compiler, language or whatever. (The same goes for comparing strings)

ArniDat
  • 534
  • 5
  • 15