(fromRational (1%5)) :: Double
Lennart Augustsson <lennart@mail.augustsson.net> writes
"S.D.Mechveliani" wrote:
the matter is in what the _language standard_ says. If it puts that `0.9' in the user program means precizely 9%10, then Lennart is right.
I quote the report:
"The floating point literal f is equivalent to fromRational (n Ratio.% d), where fromRational is a method in class Fractional and Ratio.% constructs a rational from two integers, as defined in the Ratio library. The integers n and d are chosen so that n/d = f."
I think the way Haskell handles numeric literals is pretty nice and it's important to understand what happens if you use them. :)
I confess, I do not understand from the previous letters, in what way, for example, Hugs finds Prelude> (fromRational (1%5)) :: Double 0.2 I never dealt with Floats in Haskell. And thought that a value of Double has mantissa in a binary representation. So, the interpreter has to convert a decimal 5 to a binary 101B, evaluate 1B / 101B obtaining an infinite sequence of binary digits and take the first m of them required for Double. Printing the result should yield something like 0.1999... Thank you in advance for the explanation. ----------------- Serge Mechveliani mechvel@botik.ru
At 10:02 2001-04-19 +0400, S.D.Mechveliani wrote:
Hugs finds Prelude> (fromRational (1%5)) :: Double
0.2
Double has mantissa in a binary representation. So, the interpreter has to convert a decimal 5 to a binary 101B, evaluate 1B / 101B obtaining an infinite sequence of binary digits and take the first m of them required for Double. Printing the result should yield something like 0.1999...
You've got it all correct. The trick is in the "something like" which happens during printing. The exact result would be 0.200000000000000011102230246251565404236316680908203125 which is unwieldy, and can be misleading about its precision. Those last 38 digits must not be mistaken for something useful. Fortran would show a decimal precision related to the binary precision of the DOUBLE, i.e. 2.0000000000000001e-1 In Fortran, the number of decimal digits displayed is independent of the numeric value. But this is not the only possible choice. Haskell uses a technique which is becoming more popular, in which the number of digits displayed depends on the value. It finds the minimum number of digits which will convert back to the original binary number. 0.2 when converted to binary has the same value 0.200000000000000011102230246251565404236316680908203125 therefore 0.2 is printed. -- Scott Turner p.turner@computer.org http://www.billygoat.org/pkturner
participants (2)
-
S.D.Mechveliani -
Scott Turner