必要なすべての整数除算モードを実装する関数を備えたオープンソースの C または C++ ライブラリを知っている人はいますか? 考えられる行動 (肯定的な結果の場合):
round_down, round_up,
round_to_nearest_with_ties_rounding_up,
round_to_nearest_with_ties_rounding_down,
round_to_nearest_with_ties_rounding_to_even,
round_to_nearest_with_ties_rounding_to_odd
それぞれ (偶数への丸めと奇数への丸めを除く) には 2 つのバリアントがあります
// (round relative to 0; -divide(-x, y) == divide(x, y))
negative_mirrors_positive,
// (round relative to -Infinity; divide(x + C*y, y) == divide(x, y) + C)
negative_continuous_with_positive
.
私はそれを書く方法を知っていますが、確かに誰かがすでにそうしていますか?
例として、組み込みの符号付き整数除算がゼロに向かって丸められ、組み込みのモジュラスがこれと一致していると仮定すると (C++11 で一般的であり、義務付けられているように)、
int divide_rounding_up_with_negative_mirroring_positive(int dividend, int divisor) {
// div+mod is often a single machine instruction.
const int quotient = dividend / divisor;
const int remainder = dividend % divisor;
// this ?:'s condition equals whether quotient is positive,
// but we compute it without depending on quotient for speed
// (instruction-level parallelism with the divide).
const int adjustment = (((dividend < 0) == (divisor < 0)) ? 1 : -1);
if(remainder != 0) {
return quotient + adjustment;
}
else {
return quotient;
}
}
ボーナス ポイント: 複数の引数タイプで機能します。速い; オプションでモジュラスも返します。どの引数値についてもオーバーフローしません (もちろん、0 による除算と MIN_INT/-1 を除く)。
そのようなライブラリが見つからない場合は、C++ 11 で作成してリリースし、ここの回答でリンクします。