Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to nearest integer strange results

Tags:

Is there an official specification for the round function in Haskell? In GHCi version 7.0.3 I see the following behaviour:

ghci> round (0.5 :: Double) 0 ghci> round (1.5 :: Double) 2 

Since both 0.5 and 1.5 are representable exactly as floating point numbers, I expected to see the same behaviour as in Python:

>>> round(0.5) 1.0 >>> round(1.5) 2.0 

Is there a rationale for the difference, or is it a quirk of GHCi?

like image 973
Chris Taylor Avatar asked May 24 '12 13:05

Chris Taylor


People also ask

How do you round to the nearest integer?

To round a number to the nearest whole number, you have to look at the first digit after the decimal point. If this digit is less than 5 (1, 2, 3, 4) we don't have to do anything, but if the digit is 5 or greater (5, 6, 7, 8, 9) we must round up.

What does it mean when it says round up to the nearest integer?

Rounding a number involves replacing the number with an approximation of the number that results in a shorter, simpler, or more explicit representation of said number based on specific rounding definitions. For example, if rounding the number 2.7 to the nearest integer, 2.7 would be rounded to 3.

How do you round to the nearest integer in Python?

ceil(). To round down to the nearest integer, use math. floor(). To round a number to a number of decimals, give the round() function a second argument.


1 Answers

It's in the specification. You can see it in section 6.4.6 of the Haskell report:

round x returns the nearest integer to x, the even integer if x is equidistant between two integers.

As pointed out by @dflemstr, this is in accordance with the IEEE Standard for Floating-Point Arithmetic.

like image 66
evilcandybag Avatar answered Sep 24 '22 13:09

evilcandybag