Floating point problems

Lennart Augustsson lennart at augustsson.net
Wed Aug 30 22:27:17 EDT 2006


On Aug 30, 2006, at 20:44 , Jan-Willem Maessen wrote:

>
> On Aug 30, 2006, at 6:04 PM, Lennart Augustsson wrote:
>
>>
>> On Aug 30, 2006, at 14:58 , David Roundy wrote:
>>
>>> On Wed, Aug 30, 2006 at 07:38:35PM +0100, Jamie Brandon wrote:
>>>> I recently defied my supervisor and used Haskell to write my
>>>> coursework instead of C. All went well until I needed floating  
>>>> point
>>>> and started having odd results. As far as I can tell it isn't
>>>> substantially affecting my results but it is rather embarrassing
>>>> after slagging off C so much. Here are some examples:
>>>>
>>>>         *Main> 0.2 + 0.1
>>>>         0.30000000000000004
>>>>         *Main> 0.200000000000000 + 0.100000000000000000
>>>>         0.30000000000000004
>>>>         *Main> 0.3 + 0.1
>>>>         0.4
>>>>         *Main> 0.2 + 0.1
>>>>         0.30000000000000004
>>>>         *Main> it + 0.1
>>>>         0.4
>>>>
>>>> I assume this is a result of the discrepancy between binary and  
>>>> decimal
>>>> representations of the numbers. Is there any way around? For a  
>>>> start, it
>>>> would be nice to have a simple way to get 0.1 + 0.2 == 0.3  =  True
>>>>
>>>> This is with GHC 6.4.1 and GCC 4.0.3
>>>
>>> The trouble here is that ghci is printing more digits than it really
>>> ought to be printing.
>>
>> No, I don't think it is.  Ghci is printing the number that is  
>> closest of all numbers in decimal notation to the Double in  
>> question (i.e., 0.1+0.2).  Printing it with fewer decimals would  
>> yield a different number if it was read back.
>
> I always wondered why we didn't instead ask for "the number that  
> has the fewest digits of significand which converts to the Double  
> in question."  Of course, for doubles with a single ulp of  
> difference, that's still an awfully long decimal.
The reading and printing of floating point numbers in Haskell is  
patterned after two PLDI papers (doing it in Scheme).
I think the code has exactly the property you ask for, if you expect  
conversion from Double to decimal to be sensible.


>
> I feel like I looked into this once when I was trying to understand  
> the bignum-heavy Read instance for Double in the report, and ended  
> up with a nasty headache and some fixed-point code which used cute  
> hacks and seemed to work with limited testing and the vagaries of  
> gcc as a back end.

I'm sure it can be done with less bignums, but it's quite tricky to  
get right even with bignums.

	-- Lennart



More information about the Glasgow-haskell-users mailing list