(-1)^2 x c x 2^q
s=sign bit
c=significand (or 'coefficient')
q=exponent
http://en.wikipedia.org/wiki/IEEE_754-2008
E is most accurately represented by:
6121026514868073 x 2^-51
though on my SPARC the best one gets is
6121026514868074 x 2^-51
I wanted to know how to convert a floating point number to that format using
Mathematica. The very knowledgeable and helpful Daniel Lichtblau of Wolfram
Research answered my question on sci.math.symbolic. I must admit I was impressed
how few lines of code it took him.
$ cat RealToIEEE754.m
RealToIEEE754[x_]:=Block[{s,digits,expon,c,q},
s=Sign[x];
{digits,expon}=RealDigits[x,2];
c = FromDigits[digits, 2] ;
q = expon - Length[digits] ;
{s,c,q} ]
In[1]:= <<RealToIEEE754.m
In[2]:= RealToIEEE754[Exp[1.]]
Out[2]= {1, 6121026514868074, -51}
I was wondering how elegant one could implement that in Sage.
sage: def realToIEEE754(x):
....: if x == 0: return 0, 0, 0
....: valuation, unit = x.exact_rational().val_unit(2)
....: return x.sign(), unit, valuation
....:
sage: realToIEEE754(exp(1.0))
(1, 6121026514868073, -51)
It is sad we don't have a top-level sign function.
- Robert
We do, but it's called sgn.
sage: sgn(3.0)
1
--Mike
Was there a good reason for choosing the name 'sgn'? It sems a bit
strange to me.
Dave
That's the standard mathematical notation for this function, see
http://en.wikipedia.org/wiki/Sign_function
Best,
Alex
--
Alex Ghitza -- Lecturer in Mathematics -- The University of Melbourne
-- Australia -- http://www.ms.unimelb.edu.au/~aghitza/
See http://trac.sagemath.org/sage_trac/ticket/7830 for a patch for the
following functionality:
sage: R=RealField(53)
sage: a=R(exp(1.0)); a
2.71828182845905
sage: sign,mantissa,exponent=R(exp(1.0)).representation()
sage: sign,mantissa,exponent
(1, 6121026514868073, -51)
sage: sign*mantissa*(2**exponent)==a
True
I'm not happy with the name ("representation"). What do people think?
Thanks,
Jason
Here's yet another way to do it:
sage: import mpmath
sage: b=mpmath.mpf(exp(1.0))
sage: b
mpf('2.7182818284590451')
sage: b.man # mantissa
6121026514868073
sage: b.exp # exponent
-51
Thanks,
Jason
OK, Mathematica is no shorter than Sage in this respect.
dave
Thank you. I was not aware of that - but as you probably gather, I did
not study maths,
Then there is an inconsistency with x.sign(), which seems like a problem.
Jason
"""
Ken Thompson was once asked what he would do differently if he were
redesigning the UNIX system. His reply: "I'd spell creat with an e."
"""
(http://en.wikiquote.org/wiki/Kenneth_Thompson)
Best, Gonzalo
(integer-decode-float (exp 1.0d0))
which produces 3 values:
6121026514868073
-51
1
In maxima you would have to prefix this with :lisp.
In Sage, perhaps
maxima ":lisp (integer-decode-float .... "
Though how Sage treats multiple-value returns, from lisp, I don't
know. so maybe you need
(multiple-value-list (integer-decode-float ...))