[Haskell-beginners] truncate results depend on strict/lazy
Bryan Vicknair
bryanvick at gmail.com
Tue Sep 10 02:03:50 CEST 2013
On Tue, Sep 10, 2013 at 05:26:08AM +0700, Kim-Ee Yeoh wrote:
> On Tue, Sep 10, 2013 at 5:08 AM, Bryan Vicknair <bryanvick at gmail.com> wrote:
>
> > And all of a sudden, the parsing code doesn't work again!:
> >
> > Prelude Data.Text Lib> validateVal $ pack "0.12"
> > Success (Just 11)
> >
>
> This might be due to a floating-point roundoff error since 0.12 doesn't
> have a finite binary representation.
>
> The function truncate does exactly what it says, so truncate (100 *
> 0.1199999) evaluates to 11.
>
> Are you sure you don't want "round" instead of "truncate"?
>
> -- Kim-Ee
My first thought, as always with Floats, is that there was a binary
representation problem. If it were just that I wouldn't mind, but it is the
inconsistent evaluation of the following expression that is really bothering
me:
> truncate ((0.12::Float) * (100::Float))
In GHCI, I get 12:
> let f = 0.12::Float
> truncate (f * 100)
truncate ((0.12::Float) * (100::Float))
But in my web app and in this project it gives me 11:
https://bitbucket.org/bryanvick/truncate/overview
Whatever the behavior of truncate is, given the same input it should give the
same output. In the project referenced above, the input to validateVal and
unsafeValidateVal is always "0.12", but the output is 11 for the first and 12
for the second. The only difference between the two functions is that the
unsafe version performs IO.
More information about the Beginners
mailing list