Skip to main content
Added implementations that match floating-point division and rounding
Source Link
Brent Bradburn
  • 55.7k
  • 19
  • 164
  • 191

For some algorithms you need a consistent bias when 'nearest' is a tie.

// round-to-nearest with mid-value bias towards positive infinity int idiv_nearestdiv_nearest( int n, int d ) { if (d<0) n*=-1, d*=-1; return (abs(n)+((d-(n<0?1:0))>>1))/d * ((n<0)?-1:+1); } 

This works regardless of the sign of the numerator or denominator.


If you want to match the results of round(N/(double)D) (floating-point division and rounding), here are a few variations that all produce the same results:

int div_nearest( int n, int d ) { int r=(n<0?-1:+1)*(abs(d)>>1); // eliminates a division // int r=((n<0)^(d<0)?-1:+1)*(d/2); // basically the same as @ericbn // int r=(n*d<0?-1:+1)*(d/2); // small variation from @ericbn return (n+r)/d; } 

Note: The relative speed of (abs(d)>>1) vs. (d/2) is likely to be platform dependent.

For some algorithms you need a consistent bias when 'nearest' is a tie.

// round-to-nearest with mid-value bias towards positive infinity int idiv_nearest( int n, int d ) { if (d<0) n*=-1, d*=-1; return (abs(n)+((d-(n<0?1:0))>>1))/d * ((n<0)?-1:+1); } 

This works regardless of the sign of the numerator or denominator.

For some algorithms you need a consistent bias when 'nearest' is a tie.

// round-to-nearest with mid-value bias towards positive infinity int div_nearest( int n, int d ) { if (d<0) n*=-1, d*=-1; return (abs(n)+((d-(n<0?1:0))>>1))/d * ((n<0)?-1:+1); } 

This works regardless of the sign of the numerator or denominator.


If you want to match the results of round(N/(double)D) (floating-point division and rounding), here are a few variations that all produce the same results:

int div_nearest( int n, int d ) { int r=(n<0?-1:+1)*(abs(d)>>1); // eliminates a division // int r=((n<0)^(d<0)?-1:+1)*(d/2); // basically the same as @ericbn // int r=(n*d<0?-1:+1)*(d/2); // small variation from @ericbn return (n+r)/d; } 

Note: The relative speed of (abs(d)>>1) vs. (d/2) is likely to be platform dependent.

Source Link
Brent Bradburn
  • 55.7k
  • 19
  • 164
  • 191

For some algorithms you need a consistent bias when 'nearest' is a tie.

// round-to-nearest with mid-value bias towards positive infinity int idiv_nearest( int n, int d ) { if (d<0) n*=-1, d*=-1; return (abs(n)+((d-(n<0?1:0))>>1))/d * ((n<0)?-1:+1); } 

This works regardless of the sign of the numerator or denominator.