Last active
September 15, 2021 05:38
-
-
Save OR13/20bc2044e01d512a51d0 to your computer and use it in GitHub Desktop.
Round N to nearest multiple of M
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | Ternary operator. | |
-- Usage: (i > 0) ? i $ 1 | |
(?) :: Bool -> a -> a -> a | |
True ? x = const x | |
False ? _ = id | |
-- round n to nearest multiple of m | |
roundToNearestMultiple :: Int -> Int -> Int | |
roundToNearestMultiple n m = (m >= n) ? m $ (n `div` m + 1) * m |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# edited with credit to https://gist.github.com/OR13/20bc2044e01d512a51d0#gistcomment-3745258 | |
def round_to_nearest(n, m): | |
return (n + m - 1) // m * m |
thanks! I can't say I even remember why I have this gist...
It comes up rather high on a Google search for 'python round up to the nearest multiple', so I wanted to make sure it wasn't going to trip people up. 😃
This is a good one. What about the equivalent of MROUND function in excel in which case round_to_nearest(20.46, 0.05)
should be 20.45 instead of 20.50 and round_to_nearest(20.48, 0.05)
should be 20.50 ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I can't say anything about the haskell code, but the Python code here has a syntax error in it (missing parens) and is specific to Python 2 (presumably) as the
/
division operator gives you a floating point number, not on integer.Next, it is wrong for numbers that are already multiples of
m
, e.g.round_to_nearest(24, 8)
should return 24, not 32. The correct formula is(n + m - 1) // m * m
.Corrected code:
There is no need to handle the
n <= m
case separately.It would be much simpler to just use
math.ceil()
however: