Search code examples
javascriptgoogle-chromefirefoxv8hypotenuse

Different results of Math.hypot() on Chrome and Firefox


When I run the simple calculation below the results on Chrome and Firefox slightly differ.

Chrome: 56.1124478168614

Firefox: 56.11244781686139

let x = -24.42;
let y = -50.519999999999925;
console.log(Math.hypot(x, y));

Is there a hole in the specification of Math.hypot() or is one of the browsers implementing it in a wrong way?

Edit: In Firefox Math.hypot(x, y) gives the same result as Math.sqrt(x*x, y*y), in Chrome the result from Math.hypot(x, y) is slightly different. Therefore I suspect Firefox is doing the calculation correctly.


Solution

  • Although Math.js is the same code in both browsers, different engines have different algorithms for performing basic arithmetic. For example, there are many different methods of computing a square root, and it is unlikely that two different engines would share the exact same implementation.
    There are efforts to standardise precision across engines, yet they are as of yet unsuccessful. See this article for example.
    As to why Math.hypot in Chrome would return a different value to doing the calculation manually in the same engine, Math.hypot is intended as an efficient approximation - not just a neat way of wrapping up the work into a single function. Thus, depending on the implementation, its results may differ from the actual calculation. You are right in stating that in this case, Firefox has the more numerically accurate implementation, as evidenced by your simple test.