07.26.07

Exercise 4.1

Posted in Uncategorized at 12:42 pm by admin

inchToPixel :: Float -> Int
inchToPixel x = round (100 * x)
 
inchToPixelBad :: Float -> Int
inchToPixelBad x = 100 * round x

The second definition is bad because rounding a small floating point number leads to a loss of precision in the integer. Better to multiply by 100 first, before rounding. For example, consider:

inchToPixel 2.5555 = round (100 * 2.5555) = round (255.55) = 256
inchToPixelBad 2.5555 = 100 * round 2.5555 = 100 * 3 = 300

Quite a difference in the result!

1 Comment »

  1. The Haskell School of Expression: Exercises » Exercise 4.2 said,

    July 26, 2007 at 12:52 pm

    […] Apart from anything else, the commented out version of pixelToInchBad gives an error, viz.: Instance of Fractional Int required for definition of pixelToInchBad. Assuming the second version is what the book is hinting at, this has the same issues with loss of precision that we saw in Exercise 4.1. […]

Leave a Comment