Design & Download
Your JS Library
in Seconds!!!

Snippet: frexp() & ldexp()

Written by Christopher West (cwest) on January 11, 2016.
Working with fractions and exponents of two.
var frexp;
(function(Math, log, LOG2) {
  log = Math.log;
  LOG2 = log(2);
  frexp = function(x) {
    if (isFinite(x = +x) && x !== 0) {
      var sign = x < 0 ? -1 : 1,
          pow2 = Math.floor(1 + log(x *= sign) / LOG2);
      return [sign * x / Math.pow(2, pow2), pow2];
    }
    return [x, 0];
  };
})(Math);

function ldexp(x, exp) {
  return x * Math.pow(2, exp);
}

frexp(...) API Documentation

Decomposes given floating point value arg into a normalized fraction and an integral power of two. You can also check out this page for more information about the C++ equivalent.

Parameters

  1. x {number}:
    The number to be decomposed into a normalized fraction and an integral power of two.

Returns

If -Infinity, -0, 0, Infinity or NaN are passed in an array will be returned where the first value is the value passed in and 0 is the second value. If any other number is passed in it will be decomposed and an array will be returned where the first value will be a floating point number and the second value will be an integer. Let's say that result is the returned array: result[0] * Math.pow(2, result[1]) should result in the original number passed in (x).

ldexp(...) API Documentation

Returns the result of multiplying x (the significand) by 2 raised to the power of exp (the exponent). You can also check out this page for more information about the C++ equivalent.

Parameters

  1. x {number}:
    Floating point value representing the significand.
  2. exp {number}:
    Value of the exponent.

Returns

Returns the result of multiplying x (the significand) by 2 raised to the power of exp (the exponent).