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!
One response to “Exercise 4.1”
[…] 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. […]