Skip to content

2 x problems observed in intersect.js algorithm #760

@diarmidmackenzie

Description

@diarmidmackenzie

https://github.com/tripleblindmarket/covid-safe-paths/blob/develop/app/helpers/Intersect.js

2 problems spotted when testing a Python version of the same algorithm.

// Close enough to do a detailed calculation. Using the the Spherical Law of Cosines method.
// https://www.movable-type.co.uk/scripts/latlong.html
// https://en.wikipedia.org/wiki/Spherical_law_of_cosines
//

let d =
Math.acos(
Math.sin(p1) * Math.sin(p2) +
Math.cos(p1) * Math.cos(p2) * Math.cos(deltaLambda),
) * R;

Problem 1: Based on what Wikipedia says, I think the formula should be:

let d =
Math.acos(
Math.cos(p1) * Math.cos(p2) +
Math.sin(p1) * Math.sin(p2) * Math.cos(deltaLambda),
) * R;

(sins & cos's swapped over).

image

Problem 2: In my Python code I have seen a very weird occurrence where the following values led to the value supplied to the acos being > 1 (1.0000000000000002)

Specifically I saw this when comparing distances between identical points, with specific values:

p1 = 0.0017454475853176147
p2 = 0.0017454475853176147
deltaLambda = 0.0

Presumably some rounding error in the floating point arithmetic, ends up with an impossible value > 1 for the cosine, which then causes an exception when you feed it into acos.

I don't know if the same thing can happen with Javascript, but it seems prudent to put some defensive code in: check the value to be fed into acos, and it it is > 1, set it to 1.0. This fixed the crash in my Python code.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Data ScienceFeatures/Algorithms with data science aspect to it

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions