On 4/21/07, Yozo Hida <yozo at cs.berkeley.edu> wrote:
>
> I'm fairly new to Maxima, and I currently use it to prove accuracy /
> correctness of floating point algorithms.
Welcome!
The question I have is, is there a way to convert a rational number
> to IEEE single/double precision formats and vice versa?
Rational to float: float(...).
Float to its exact rational representation: rationalize(...)
Float to a "nice" rational: rat(...)
float(1/7) => 0.14285714285714
rationalize(float(1/7)) => 2573485501354569/18014398509481984
1/7 - % => 1/126100789566373888
factor(%) => 1 / (2^54 * 7)
rat(float(1/7)) => 1/7
Rat chooses the smallest-denominator rational within < ratepsilon > of its
argument using continued fractions. Ratepsilon by default is 2.0e-8 (I
think it should be much smaller by default, but you can easily change it
anyway).
53! - float(53!) gives me 0.0 [with Maxima 5.11].
Approximate representations (float and bfloat) are contagious, so that
expression evaluates as float(53!) - float(53!), which is of course 0.0. To
calculate the exact different, try
53! - rationalize(float(53!)) =>
79506758988047003931433848776051802663185202089558016
generally, is there a routine to transform any rational number x to a
> nearest representable floating point number with a given radix B and
> mantissa length L
Not built-in, but it is easy enough to write. First reduce the rational
number to the range 1/B..1, e.g.
( exp: 0,
while x > 1 do (x: x/R, exp: exp+1),
while x < 1/B do (x: x*R, exp: exp - 1) )
then calculate the mantissa
mantissa: floor( 1/2 + x * B^L)
...using the simple rounding system. If you want IEEE rounding or whatever,
you'll have to work a little harder.
I hope this helps.
-s