Exercise 4.1


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”

Leave a Reply

Your email address will not be published. Required fields are marked *