int除法舍入库

int division rounding library?

本文关键字:舍入 除法 int      更新时间:2023-10-16

有人知道一个开源的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

每个(除了从整数到偶数和从整数到奇数)都有两个变体

// (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;
  }
}

加分:适用于多种参数类型;快速的可选地还具有返回模量;任何参数值都不要溢出(当然除了除以零和MIN_INT/-1)。

如果我找不到这样的库,我会用C++11编写一个库,发布它,并在这里的答案中链接到它。

所以,我写了一些东西。实现通常是丑陋的模板和逐位代码,但它运行良好。用法:

divide(dividend, divisor, rounding_strategy<...>())

其中CCD_ 1是示例策略;请参阅我的问题或源代码中的变体列表。https://github.com/idupree/Lasercake/blob/ee2ce96d33cad10d376c6c5feb34805ab44862ac/data_structures/numbers.hpp#L80

仅依赖于C++11[*],单元测试(使用Boost Test框架)从https://github.com/idupree/Lasercake/blob/ee2ce96d33cad10d376c6c5feb34805ab44862ac/tests/misc_utils_tests.cpp#L38

它是多态的,速度不错,不会溢出,但目前不返回模数。

[*](和boost::make_signed和boost::enable_if_c上,用std::make_signed和std::enable_if替换它们是微不足道的,在我们的caller_error_if()上,它可以用assert()或if(..){throw.}替换或删除。您可以忽略并删除文件的其余部分,假设您对其中的其他内容不感兴趣。)

每个divide_ impl的代码可以通过用例如int替换每个T和用CONSTANT替换T(CONSTANT)来适应C。在round_to_nearest_*变体的情况下,您可能希望将舍入类型作为运行时参数,或者创建代码的六个副本(它处理的每个不同舍入变体都有一个副本)。该代码依赖于向零取整的"/",这是常见的,也由C11(标准草案N1570 6.5.5.6)和C++11指定。对于C89/C++98的兼容性,它可以使用stdlib.hdiv()/ldiv(),它们保证向零取整(请参阅http://www.linuxmanpages.com/man3/div.3.php,http://en.cppreference.com/w/cpp/numeric/math/div)