RFC: Fixing floating point conversions.

Nick Bowler nbowler at elliptictech.com
Fri Feb 26 17:37:04 EST 2010


On 14:23 Thu 25 Feb     , John Meacham wrote:
> On Thu, Feb 25, 2010 at 10:40:48AM -0500, Nick Bowler wrote:
> > *** Idea #1 ***
> > 
> > Add two methods to the RealFloat class:
> > 
> >   toDouble   :: RealFloat a => a -> Double
> >   fromDouble :: RealFloat a => Double -> a
> > 
> > and a function:
> > 
> >   toFloating :: (RealFloat a, RealFloat b) => a -> b
> >   toFloating = fromDouble . toDouble
> 
> That is exactly how I solved it in the jhc libraries. 
> 
> Though, I may switch to using a 'FloatMax' type that is always aliased
> to the largest floating point type available, now that Float128 and
> Float80 are potentially available. (but it would just be an alias for
> Double for now)

Indeed, a type alias sounds like a good improvement to idea #1 for
exactly the reasons that you mention.

However, for an actual amendment to the standard, I'd like to see a
solution which allows libraries to define their own instances of the
numeric classes.  Imagine that someone wants to create a library which
implements decimal floating point arithmetic.  With something like
toDouble or toFloatMax, the author is faced with two major obstacles:
 
  * After creating new types, 'FloatMax' (which can't be redefined)
    might not be the "max" anymore.
  * When 'FloatMax' has a different radix, there is going to be
    loss of information when converting to it.  For example, 1/5 is
    exactly representable in decimal floating point, but not in binary
    floating point with any finite number of significand digits.

The end result is that 'toFloating' is not suitable for the decimal
floating point library, so the author would have to invent her own
conversion method.

It is for this reason that I prefer something along the lines of idea #2
with a "generic" intermediate type.  Nevertheless, #1 (with or without
FloatMax) is still a /huge/ improvement over the status quo.

-- 
Nick Bowler, Elliptic Technologies (http://www.elliptictech.com/)


More information about the Haskell-prime mailing list