1

I have a little problem with my distance calculation function, here is a screenshot of a playground where we see that distance variable == NaN (instead of 0) when tsum == 1

playground showing problem

in fact at runtime (in my real app, in simulator), t1 + t2 + t3 == 1.0000000000000002

t1 + t2 + t3 == 1.0000000000000002

its really strange because when i manually calculate it, i have 1

manual calculation

but ios seems to not agree that. Can you explain that ?

P.S : Here is a link to the playground https://drive.google.com/drive/folders/0B6uRRn4bFMAeN3kwSVc4dUVQcDQ?usp=sharing

P.S.2 : i give a screenshot to prove that i'm not manipulating values: complete screenshot at runtime

4x10m
  • 842
  • 8
  • 11
  • Just what is your question--why you get a `NAN` distance or why `t1 + t2 + t3` is not `1`? – Rory Daulton Apr 29 '17 at 22:47
  • i add a line "tsum > 1" in playground and it say true but why it printed just 1 before ? Did i need to solve that with "boiler plate code" tt = tsum > 1 ? 1 : tsum (and same with -1 maybe) ? – 4x10m Apr 29 '17 at 22:47
  • i guess i know why i have a NaN (because tsum > 1 and its a math exception with acos) but i don't understand why t1+t2+t3 (so tsum) != 1 and further > 1 – 4x10m Apr 29 '17 at 22:50
  • Computers use binary math, so you won't always get accurate results when doing arithmetic with decimal numbers. Depending on your precison needs, rounding it might solve your problem. – John Montgomery Apr 29 '17 at 22:53
  • Ok but why google calc and playground shows just 1 ? – 4x10m Apr 29 '17 at 22:54
  • 2
    Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Alexander Apr 30 '17 at 01:04
  • OK thank you very much, it's strange that after almost 10 year of coding, I never ear this story :0. Especially with almost 5 year of high school informatique computing curses... – 4x10m Apr 30 '17 at 08:21
  • Why did someone downvote? I'm now at 14 of reputation which make me losing the right to post pictures... – 4x10m Apr 30 '17 at 08:22

1 Answers1

3

if you are looking for something which works on apple platforms, use

import CoreLocation

let lat0 = 0.0
let lon0 = 0.0

let lat1 = 90.0
let lon1 = 180.0

let l0 = CLLocation(latitude: lat0, longitude: lon0)
let l1 = CLLocation(latitude: lat1, longitude: lon1)

let distance = l0.distance(from: l1) // in meters

if you don't like it, replace your formula

d = acos( sin φ1 ⋅ sin φ2 + cos φ1 ⋅ cos φ2 ⋅ cos Δλ ) ⋅ R

with

a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)

c = 2 ⋅ atan2( √a, √(1−a) )

d = R ⋅ c

which is known as haversine formula. with help of atan2 function you avoid floating point math trouble

user3441734
  • 16,722
  • 2
  • 40
  • 59