Double and rational number problem

I am writing a function in which I need to read a string containing a floating point number and return it to Rational. But when I do toRational (read input :: Double), it does not turn on, for example: 0.9in 9 % 10, as expected, but instead 81 .....% 9007 ... thanks

+3
source share
2 answers

This is the correct behavior. The number is 0.9not represented in the form Double, and not in Haskell, C or Java. This is due to the fact that Doublethey Floatuse base 2: they can accurately represent only a certain subset of binary fractions.

, Numeric readFloat. ( ReadS), . :

import Numeric
myReadFloat :: String -> Rational -- type signature is necessary here
myReadFloat str =
    case readFloat str of
      ((n, []):_) -> n
      _ -> error "Invalid number"

, :

> myReadFloat "0.9"
9 % 10
+10

, -10. , 0,9, 0,9, . , - .

+1

All Articles