Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Text.Megaparsec.Byte.Lexer.decimal returns wrong value for Float #479

Open
jchia opened this issue May 11, 2022 · 2 comments
Open

Text.Megaparsec.Byte.Lexer.decimal returns wrong value for Float #479

jchia opened this issue May 11, 2022 · 2 comments
Labels

Comments

@jchia
Copy link

jchia commented May 11, 2022

ghci> parse (decimal @() @ByteString @_ @Float) "" "655361200000"
Right 6.5536125e11
ghci> (== 655361250000) <$> parse (decimal @() @ByteString @_ @Float) "" "655361200000"
Right True
ghci> (== 655361200000) <$> parse (decimal @() @ByteString @_ @Float) "" "655361200000"
Right False
ghci> (subtract $ fromIntegral @_ @Float 655361200000) <$> parse (decimal @() @ByteString @_ @Float) "" "655361200000"
Right 65536.0

The Float value produced is not equal to what fromIntegral @_ @Float 655361200000 returns.

It appears that decimal accumulates floating-point errors during parsing so that the final Float result is wrong. (Given the limited precision of Float, error is expected but the result is further from the perfectly accurate value than necessary.) The error probably accumulates from lossy arithmetic performed for each input character, including the (* 10).

Double is likely similarly affected, but I have not constructed a counter-example, which probably requires more digit than Float counter-example.

@mrkkrp
Copy link
Owner

mrkkrp commented May 29, 2022

Yeah, this is not ideal. IIRC I mostly copied the implementation from attoparsec. I'm going to add a warning to the docs for now.

@olafklinke
Copy link
Contributor

Wouldn't it help if decimal first parses into a non-lossy type such as Integer and then used fromInteger? For the same reason the float parser uses Scientific under the hood.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants