math-fround.js 893 B

1234567891011121314151617181920212223242526272829
  1. 'use strict';
  2. var sign = require('../internals/math-sign');
  3. var abs = Math.abs;
  4. var pow = Math.pow;
  5. var EPSILON = pow(2, -52);
  6. var EPSILON32 = pow(2, -23);
  7. var MAX32 = pow(2, 127) * (2 - EPSILON32);
  8. var MIN32 = pow(2, -126);
  9. var roundTiesToEven = function (n) {
  10. return n + 1 / EPSILON - 1 / EPSILON;
  11. };
  12. // `Math.fround` method implementation
  13. // https://tc39.es/ecma262/#sec-math.fround
  14. // eslint-disable-next-line es/no-math-fround -- safe
  15. module.exports = Math.fround || function fround(x) {
  16. var n = +x;
  17. var $abs = abs(n);
  18. var $sign = sign(n);
  19. var a, result;
  20. if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
  21. a = (1 + EPSILON32 / EPSILON) * $abs;
  22. result = a - (a - $abs);
  23. // eslint-disable-next-line no-self-compare -- NaN check
  24. if (result > MAX32 || result !== result) return $sign * Infinity;
  25. return $sign * result;
  26. };