Haskell: 9.3 - (2 * 4.5) => 0.3000000000000007

I expected 0.3

?

6 Replies

@dragolov:

I expected 0.3

?

Welcome to IEEE 754 double-precision floating point arithmetic. http://en.wikipedia.org/wiki/IEEEfloatingpoint Basic gist is don't expect anything to ever be exact :) .

It's been a long time since I touched Haskell in university, but in most languages, I'd say "Don't use double if you need a precise answer, use the language's decimal implementation."

Curiously,

Python 2.6.5 (r265:79063, Oct  1 2012, 22:04:36) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 9.3 - (2 * 4.5)
0.30000000000000071

$ irb -v
irb 0.9.5(05/04/13)
$ irb
irb(main):001:0> 9.3 - (2 * 4.5)
=> 0.300000000000001

$ perl -v

This is perl, v5.10.1 (*) built for x86_64-linux-gnu-thread-multi
...
$ perl -e "print 9.3 - (2 * 4.5);"
0.300000000000001

$ bc -v bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. $ echo 'scale=100; 9.3 - (2 * 4.5)' | bc .3

:)

IIRC the latest version of Haskell now makes all internal calculations using Roman numerals instead of binary, negating this problem.

James

That sounds about right for Haskell.

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct