Alex Rivera | Logout

C++ functions for integer division with well defined rounding strategy

Asked 2011-11-15T13:21:42.487
10

I want something in C++ that lets me do efficient integer division with specified rounding behavior, something like this:

div_down(-4,3)        ==> -2
div_up(4,3)           ==> 2
div_to_zero(-4,3)     ==> -1
div_to_nearest(5,3)   ==> 2

I'd like it to detect target machine behavior at compile time and generate the appropriate optimal implementations. Something similar for modulus would also be nice, abstracting out the undefined behavior for negative operands at compile time.

Does this exist?

If not, what's a nice way to make it? I can think of a few possible approaches:

  • Try to implement them as single expressions that statically optimize
  • Use constant expressions to detect target behavior and choose from multiple implementations, parhaps using templates (but how exactly?)
Edit
Report

1 Answer

6

This is what I've got so far, with the precondition d > 0. They all seem to work, but can they be simplified?

int div_down(int n, int d) {
  if (n < 0) {
    return -((d - n - 1) / d);
  } else {
    return n / d;
  }
}

int div_up(int n, int d) {
  if (n < 0) {
    return -(-n / d);
  } else {
    return (n + d - 1) / d;
  }
}

int div_to_zero(int n, int d) {
  return n / d;
}

int div_to_nearest(int n, int d) {
  if (n < 0) {
    return (n - d/2 + 1) / d;
  } else {
    return (n + d/2) / d;
  }
}
answered 2011-11-16T20:53:06.800

Your Answer