paulmillr / es6-shim

ECMAScript 6 compatibility shims for legacy JS engines
http://paulmillr.com
MIT License
3.11k stars 387 forks source link

Accuracy of Math.cbrt #330

Closed Yaffle closed 9 years ago

Yaffle commented 9 years ago

I have added 2 lines of code:

var cbrt = function (value) {
  value = Number(value);
  if (value === 0) { return value; }
  var negate = value < 0, result;
  if (negate) { value = -value; }
  result = Math.pow(value, 1 / 3);
  // from http://en.wikipedia.org/wiki/Cube_root#Numerical_methods
  result = (value / (result * result) + 2 * result) / 3;
  return negate ? -result : result;
};

var error = function (x, value) {
  return Math.abs(1 - x / value) / Number.EPSILON; // error in number of ulps (http://en.wikipedia.org/wiki/Unit_in_the_last_place)
};

console.log(error(Math.pow(2, 341), Math.cbrt(Math.pow(2, 341 * 3))));
console.log(error(Math.pow(2, 341), cbrt(Math.pow(2, 341 * 3))));

console.log(error(Math.pow(2, -340), Math.cbrt(Math.pow(2, -340 * 3))));
console.log(error(Math.pow(2, -340), cbrt(Math.pow(2, -340 * 3))));

//! WARNING: subnormals
console.log(error(Math.pow(2, -358), Math.cbrt(Math.pow(2, -358 * 3))));
console.log(error(Math.pow(2, -358), cbrt(Math.pow(2, -358 * 3))));
ljharb commented 9 years ago

Closed via https://github.com/paulmillr/es6-shim/commit/5a7f3d770775a895b2962232622aeb7a49a8335e / #335