Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

There are actually as many cases as there are rounding modes, which is seven, and for most of them unlike `mod` and `rem` there's no common name for these remainder operations:

- RoundNearest

- RoundNearestTiesAway

- RoundNearestTiesUp

- RoundToZero — rem, div

- RoundFromZero

- RoundUp

- RoundDown — mod, fld (i.e. floor(x/y) but without incorrect corner cases)

Most languages have no way of doing most of these, but then again, they're mostly pretty useless. They're really only useful when you're pairing division with a specific kind of rounding with a remainder that needs to match. Example of whacky remainder behavior in the "familiar" RoundNearest mode (default rounding mode for floating point):

    julia> [k => rem(k, 4, RoundNearest) for k=-6:6]
    13-element Vector{Pair{Int64, Int64}}:
     -6 =>  2
     -5 => -1
     -4 =>  0
     -3 =>  1
     -2 => -2
     -1 => -1
      0 =>  0
      1 =>  1
      2 =>  2
      3 => -1
      4 =>  0
      5 =>  1
      6 => -2
Wild, huh? Output range for modulus 4 is -2:2 and whether you get -2 or 2 alternates with each cycle around the ring. (Of course, Julia has comprehensive support for all of these because we're a bunch of nerds for this kind of thing.)


> rem (3, 4) => -1

Dear God no why?! I thought my confusion around modulus could not get any worse :)




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: