Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two identical Double value return false Swift 3

Tags:

ios

swift

I tried to compare two identical latitude, which is of type Double, and when I print the result, it's evaluated as false.

print("spot latitude: " + String(spot.location.latitude))
print("first object: " + String(firstSpot.location.latitude))  
print(spot.location.latitude == firstSpot.location.latitude)

Output:

spot latitude: 32.8842183049047
first object: 32.8842183049047
false

Anyone has any idea what's going on?

like image 807
Kesong Xie Avatar asked May 11 '17 09:05

Kesong Xie


1 Answers

Comparing equality in doubles rarely gave you the expected answer this is due to how doubles are stored. You can create custom operators, keeping in mind that you should work with sort of accuracy.
To know more you can check this answer, even if it speaks about ObjC the principles are super valid.
Since I had the same problem checking online I've found this answer on the apple dev forum.
This function should do the trick, you can easily create a custom operator:

 func doubleEqual(_ a: Double, _ b: Double) -> Bool {
    return fabs(a - b) < Double.ulpOfOne
}

I've tried to convert from swift 2.x to 3.x it seems that the macro DBL_EPSILON is not available anymore.

like image 159
Andrea Avatar answered Oct 22 '22 02:10

Andrea