7
$\begingroup$

I found this and this on this StackExchange as to why Mathematica rounds half to even, which means that

Round[{0.5, 1.5, 2.5, 3.5, 4.5}]

gives

{0, 2, 2, 4, 4}

but now I am interested in rounding half down, which would be a function such that

RoundDown[{7.49, 7.5, 7.51}]

gives

{7, 7, 8}

I don't think it exists since I searched a lot and didn't find anything, so I was wondering as to how would one code such a function efficiently (I need to run it some millions of times)?

$\endgroup$
11
$\begingroup$
ClearAll[roundDown]
roundDown = Ceiling[# - 1/2] &; (* thanks: @MichaelE2 *)

roundDown @ {7.4999, 7.5, 7.51}
(* or roundDown[{7.4999, 7.5, 7.51}] *)

{7, 7, 8}

$\endgroup$
  • $\begingroup$ That's short and efficient, thanks! As a note for future users it also works with roundDown[{7.4999, 7.5, 7.51}] $\endgroup$ – viiv Jan 3 '18 at 6:48
  • $\begingroup$ @viiv, my pleasure. Thank you for the accept. $\endgroup$ – kglr Jan 3 '18 at 7:00
  • 1
    $\begingroup$ @viiv One might want to use 1/2 instead of 0.5. E.g. try rd1 = Ceiling[# - 1/2] &; rd2 = Ceiling[# - 0.5] &; {rd1[3/2 + 2^-53], rd2[3/2 + 2^-53]}. $\endgroup$ – Michael E2 Feb 20 '18 at 12:17
  • $\begingroup$ @MichaelE2, very good point. $\endgroup$ – kglr Feb 20 '18 at 12:27
  • $\begingroup$ Indeed, it's all about those edge cases. Fortunately I never went that deep into the precision, I was limited to floats. $\endgroup$ – viiv Feb 20 '18 at 12:46
2
$\begingroup$

Adding a note to kglr's answer, consider

n = 50*4.65

roundDown[n]

233

An improvement could be

rd[n_] := Ceiling[With[{r = Round[#]}, r + Chop[# - r]] &[n - 0.5]]

rd[n]

232

$\endgroup$
  • $\begingroup$ But 50*4.65 equals 232.50000000000003` , so shouldn't it round to 233? What if the number is exactly 232.50000000000003? $\endgroup$ – Michael E2 Feb 20 '18 at 12:59
  • $\begingroup$ In practical situations I have encountered I would require 50*4.65 = 232.5. $\endgroup$ – Chris Degnen Feb 20 '18 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.