on master help sign in
Make fromText of Float more accurate, relax accuracy for Float and Double tests
commit47a30c6411c517ca5e0faa9f9b5803aad233530a authorChristian Marie <christian@ponies.io> dateTue 17 Mar 2015, 12:08 (12 years ago) parent3311cbd
2 files changed+14−3
src/Servant/Common/Text.hs+4−1 test/Servant/Common/TextSpec.hs+10−2
src/Servant/Common/Text.hs+4−1
@@ -11,6 +11,7 @@ import Data.String.Conversions (cs)
1111import Data.Text (Text)
1212import Data.Text.Read (Reader, decimal, rational, signed)
1313import Data.Word (Word, Word16, Word32, Word64, Word8)
14+import GHC.Float (double2Float)
1415
1516-- | For getting values from url captures and query string parameters
1617-- Instances should obey:
@@ -130,7 +131,9 @@ instance ToText Double where
130131 toText = cs . show
131132
132133instance FromText Float where
133− fromText = runReader rational
134+ -- Double is more practically accurate due to weird rounding when using
135+ -- rational. We convert to double and then convert to Float.
136+ fromText = fmap double2Float . runReader rational
134137
135138instance ToText Float where
136139 toText = cs . show
test/Servant/Common/TextSpec.hs+10−2
@@ -55,11 +55,19 @@ spec = describe "Servant.Common.Text" $ do
5555 it "holds for Integer" $
5656 property $ \x -> textLaw (x :: Integer)
5757
58+ -- The following two properties are only reasonably expected to hold up
59+ -- to a certain precision.
60+ --
61+ -- http://en.wikipedia.org/wiki/Floating_point#Internal_representation
5862 it "holds for Double" $
59− property $ \x -> textLaw (x :: Double)
63+ property $ \x ->
64+ x < 1.0e15 && x > 1.0e-16 ==>
65+ textLaw (x :: Double)
6066
6167 it "holds for Float" $
62− property $ \x -> textLaw (x :: Float)
68+ property $ \x ->
69+ x < 1.0e7 && x > 1.0e-7 ==>
70+ textLaw (x :: Float)
6371
6472textLaw :: (FromText a, ToText a, Eq a) => a -> Bool
6573textLaw a = fromText (toText a) == Just a