Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ugly doubles - why 2.9000000000000004 instead of 2.9? [duplicate]

Tags:

haskell

when I do 5.2 - 2.3 in ghci I'll get 2.9000000000000004 instead of 2.9. Also such ugly (and for a human WRONG) results shows up on other places when working with Double or Float.

Why does this happen? (this is just for curiosity, not my real question)

My real question: How do I tell ghci to not do that, and show the results of Operations on Doubles just as any other programming language (and calculator) would and just as every 15 year old would write them?

This is just so annoying when I use ghci as a nice calculator and work on lists on which I perform such operations.

map ((-)2.3) [4.0, 3.8, 5.2, 6.4, 1.3, 8.3, 13.7, 9.0, 7.5, 2.4]
[-1.7000000000000002,-1.5,-2.9000000000000004,-4.1000000000000005,0.9999999999999998,-6.000000000000001,-11.399999999999999,-6.7,-5.2,-0.10000000000000009]

This just doesn't help when using the numbers on a piece of paper afterwards

Thanks in advance :)

like image 810
Dender Avatar asked Jul 21 '13 07:07

Dender


1 Answers

Why does this happen?

Because certain floating point numbers cannot be represented by a finite number of bits without rounding . Floating-point numbers have a limited number of digits, they cannot represent all real numbers accurately: when there are more digits than the format allows, the leftover ones are omitted - the number is rounded.

You should probably read What Every Computer Scientist Should Know About Floating-Point Arithmetic and this answer.

like image 145
AllTooSir Avatar answered Mar 25 '23 02:03

AllTooSir