0

I'm studying Javascript and I was solving a problem that involves a mathematical computation with floating numbers. I kind of heard that Javascript is weird in treating floating numbers but I was surprised when I saw its impact was this dynamic. How should I have done to get the right number for my answer? What do I need to know, to prevent this error from my future calculation? I appreciate for your help, and thank you for your time.

var merge = function(array1, array2, callback) {
var result = [];
for (var i = 0; i < array1.length; i++) {
    result.push(callback(array1[i], array2[i]));
}
return result;
};

var euclid = function(coords1, coords2) {
var myCoords = merge(coords1, coords2, function(a, b){
    return a - b;
});
return Math.sqrt(myCoords[0]^2 + myCoords[1]^2);
};

var x = euclid([1.2, 3.67], [2.0, 4.4]);

// x should now equal approximately 1.08

But instead I got:

euclid([1.2, 3.67], [2.0, 4.4]);
// -> 1.7320508075688772
KyleC
  • 159
  • 1
  • 2
  • 10
  • As a general guideline, when you think a program isn't computing something correctly, use some `console.log` (or `println`) statements to figure out where the numbers start going wrong. You should have been able to figure out that `myCoords[0]^2` was the problem, even if you didn't understand why it was the problem. – Teepeemm May 22 '15 at 14:24

1 Answers1

2

If you're wanting to square a number, it's not x^2 - that's a bitwise xor.

You need Math.pow(x, 2).

RichieHindle
  • 272,464
  • 47
  • 358
  • 399