Ptolemy2002
Ptolemy2002

Reputation: 145

Distance function Returning the wrong thing

For a while now, I have been trying to code a function that can calculate the distance between 2 points. I used this site: http://www.mathwarehouse.com/calculators/distance-formula-calculator.php to find the formula, but it kept returning different numbers. To put this into perspective, the site said that the distance from (0,0) and (50,100) was 111.80339887498948, and my computer said it was 7.483314773547883. I'm pretty sure the site is correct, but I have tried many algorithms and can't get it to return the same thing as the site did. Here is my code:

var distance = function(x1, y1, x2, y2) {
    var a = x2 - x1;
    a ^= 2;
    var b = y2 - y1;
    b ^= 2;
    var c = a + b;
    return Math.sqrt(c);
};

Can you tell me why this is saying the wrong thing?

Upvotes: 1

Views: 562

Answers (2)

Craig Ayre
Craig Ayre

Reputation: 1173

^ is the bitwise XOR operator in JavaScript, so ^= 2 isn't doing what you expect.

The exponential operator (**) exists in ES2016, but unless you are using a transpiler it might not have the browser compatibility you are after.

A few alternatives:

Multiplication

var distance = function (x1, y1, x2, y2) {
  var dx = x2 - x1;
  var dy = y2 - y1;

  return Math.sqrt(dx*dx + dy*dy);
}

Using Math.pow

var distance = function (x1, y1, x2, y2) {
  var dx = x2 - x1;
  var dy = y2 - y1;

  return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}

Using exponential operator

var distance = function (x1, y1, x2, y2) {    
  return Math.sqrt(dx**2 + dy**2);
}

Upvotes: 2

casraf
casraf

Reputation: 21684

You should use Math.pow to use exponents:

function distance(x1, y1, x2, y2) {
    var a = Math.pow(x2 - x1, 2);
    var b = Math.pow(y2 - y1, 2);
    return Math.sqrt(a + b);
};

console.log(distance(0,0,0,50))

Upvotes: 0

Related Questions