Note that there are some explanatory texts on larger screens.

plurals
  1. POExtracting the exponent and mantissa of a Javascript Number
    primarykey
    data
    text
    <p>Is there a reasonably fast way to extract the exponent and mantissa from a Number in Javascript?</p> <p>AFAIK there's no way to get at the bits behind a Number in Javascript, which makes it seem to me that I'm looking at a factorization problem: finding <code>m</code> and <code>n</code> such that <code>2^n * m = k</code> for a given <code>k</code>. Since integer factorization is in NP, I can only assume that this would be a fairly hard problem.</p> <p>I'm implementing a GHC plugin for generating Javascript and need to implement the <code>decodeFloat_Int#</code> and <code>decodeDouble_2Int#</code> <a href="http://www.haskell.org/ghc/docs/7.2.2/html/libraries/ghc-prim-0.2.0.0/GHC-Prim.html" rel="noreferrer">primitive operations</a>; I guess I could just rewrite the parts of the base library that uses the operation to do wahtever they're doing in some other way (which shouldn't be too hard since all numeric types have Number as their representation anyway,) but it'd be nice if I didn't have to.</p> <p>Is there any way to do this in an even remotely performant way, by some dark Javascript voodoo, clever mathematics or some other means, or should I just buckle down and have at the base library?</p> <p><strong>EDIT</strong> Based on ruakh's and Louis Wasserman's excellent answers, I came up with the following implementation, which seems to work well enough:</p> <pre><code>function getNumberParts(x) { if(isNaN(x)) { return {mantissa: -6755399441055744, exponent: 972}; } var sig = x &gt; 0 ? 1 : -1; if(!isFinite(x)) { return {mantissa: sig * 4503599627370496, exponent: 972}; } x = Math.abs(x); var exp = Math.floor(Math.log(x)*Math.LOG2E)-52; var man = x/Math.pow(2, exp); return {mantissa: sig*man, exponent: exp}; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload