Frage

I need to find the Spherical Distance of two coordinates using Javascript. I am using Wolfram a lot for this project and found this formula d=cos^(-1)(P·Q) [reference: http://mathworld.wolfram.com/SphericalDistance.html]. So I know that P·Q is the dot product of the two coordinates in question. This leads to finding the dot product which I found as DotProduct = (x1*x2 + y1*y2 + z1*z2) [reference: http://en.wikipedia.org/wiki/Dot_product]. So I put together the following method and get NaN (Not a Number) every time.

        function ThreeDimensionalDistance(x1,y1,z1,x2,y2,z2){

            return Math.acos(x1*x2 + y1*y2 + z1*z2);

        }

Here are two sets of sample data I use and I can't figure out why I get NaN. Am I missing something small, do I need to convert my numbers to something for them to work with arc cos? Thank you in advance for any help.

Sample 1 X:-1.7769265970284516,Y:-5.129885707200497,Z:-2.554761143401265 X:-0.8336414256732807,Y:-1.9876462173033347,Z:5.599491449072957 Distance: NaN Sample 2 X:-0.8336414256732807,Y:-1.9876462173033347,Z:5.599491449072957 X:0.8447772905770565,Y:4.252407300473133,Z:4.147696165367961 Distance: NaN

War es hilfreich?

Lösung

I've done some math, so try the following out:

function threeDimensionalDistance(x1, y1, z1, x2, y2, z2) {
    // Assume that the points are on the same sphere
    var radius = Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1);

    // Calculate normalized spherical distance
    var dotProduct = x1 * x2 + y1 * y2 + z1 * z2;
    var normalizedDistance = Math.acos(dotProduct / (radius * radius));

    // Calculate actual distance
    var distance = normalizedDistance * radius;

    return distance;
}

One minor change that I made was renaming your method to begin with a lowercase letter, to follow standard JavaScript style guidelines.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top