Can't compare two CLLocationCoordinate2Ds (negative zero??)
Asked Answered
D

1

1

I'm having the hardest time comparing two (what should be identical) CLLocationCoordinate2D structs in my iOS app. For some reason no matter how I compare them, the latitude just won't say it's equal.

The code:

double dlat = self.mapView.centerCoordinate.latitude - self.centerOnNextView.coordinate.latitude;
double dlong = self.mapView.centerCoordinate.longitude - self.centerOnNextView.coordinate.longitude;
NSLog(@"dlat: %f dlong: %f, dlat == 0.0: %d, dlat == -0.0: %d, dlong == 0.0: %d, dlong == -0.0: %d",
    dlat, dlong, dlat == 0.0, dlat == -0.0, dlong == 0.0, dlong == -0.0);
if ( ( dlat == 0.0 || dlat == -0.0 ) && ( dlong == 0.0 || dlong == -0.0 ) ) {
    NSLog(@"WE ARE EQUAL!");
}

I even tried if ( [@(dlat) isEqualToNumber:@(0)] && [@(dlong) isEqualToNumber:@(0)] ) as the comparison check, but it failed too.

Here's the output:

dlat: -0.000000
dlong: 0.000000
dlat == 0.0: 0 (false)
dlat == -0.0: 0 (false)
dlong == 0.0: 1 (true)
dlong == -0.0: 1 (true)

For some reason I just keep getting that negative zero in there and nothing will compare against it. What the heck can I do to get these things to compare?!

Daggett answered 13/8, 2013 at 4:19 Comment(2)
What, nobody's on at 9:30 on a monday night? XDDaggett
It is likely that dlat is not 0. It might be that the precision of your printf is rounding it down for display.Exercitation
B
3

dlat does not have the value of 0.0. Use %e when printing instead of %f to see the difference.

Comparing a number to 0.0 as in dlat == 0.0 gets the same result as dlat == -0.0. No need to do both compares.


More on -0
0.0 and -0.0 have the same numeric value and compare just like each other in the six compare operators >=, >, ==, !=, <, <=.

If one must distinguish between the zeros, one could use int signbit() or memcmp(). Many methods exist.

Boast answered 13/8, 2013 at 5:12 Comment(2)
You're right, it's actually -7.105427e-15 for some reason, even though I actually set the center coordinate to the same value previously. Strange indeed. I guess the only way is to do a < comparison.Daggett
1. Either self.mapView.centerCoordinate.latitude or self.centerOnNextView.coordinate.latitude of type float? 2. Try %a for precise hexadecimal notation. Likely your values differ by 1 bit.Boast

© 2022 - 2024 — McMap. All rights reserved.