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 
1
  • 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. Commented May 22, 2015 at 14:24

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Good catch. I was just about to close this as a dupe of "Is floating point math broken"
Thank you for your answer. I hadn't have a clue where to look to fix my error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.