Teja Nandamuri
Teja Nandamuri

Reputation: 11201

How to use approximately equal operator in objective-c?

I am not sure how to do achieve this logic.

I have an array of numbers:

 num = @ [0,0.5,1,1.5,2...,12.5,13,13.5,14,14.5,15,15.5.....75];

These numbers are increased with a difference of .5

and I have a result number 'x'.

I want to find out which number in the array is the close match to the 'x' .

Which mathematical operator should I use ? much less << ? or approximately equal ~~ operator in objective-c ?

I can do if (x<<y) in xcode but I cannot do x ~~ y.

At the moment I'm using the following way suggested in here:

static bool CloseEnoughForMe(double value1, double value2, double acceptableDifference)
{
    return fabs(value1 - value2) <= acceptableDifference;
}

Is there any simpler method that objective-c provides ?

Upvotes: 0

Views: 1623

Answers (1)

rmaddy
rmaddy

Reputation: 318794

There are no such operators in Objective-C (or C). You will have to do your own checking. Since each number in your array is 0.5 from the next value, you know the number you wish to check will be closest to a value in the array +/- 0.25.

Something like this perhaps:

double x = ... // The number to check
NSArray *numbers = @[ @0, @0.5, @1, @1.5, ..., 75 ]; // Your array of numbers
for (NSNumber *number in numbers) {
    if (x >= [number doubleValue] - 0.25 || x < [number doubleValue] + 0.25) {
        NSLog(@"%f is closest to %@", x, number);
        break;
    }
}

You'll need to add a little extra logic if x is less than -0.5 or greater than 75.5.

Upvotes: 3

Related Questions