int除法舍入库
int division rounding library?
有人知道一个开源的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)
- C++将浮点指针值舍入为小数位数
- Boost::posix_time::ptime舍入到给定的分钟数
- 浮点定向舍入和优化
- 为什么输出精度没有正确舍入?
- 使用设置精度时如何阻止数字向上舍入?
- 如何在使用 MPFR 时在提升多精度中设置舍入模式
- OpenCV 细分一致的 Rect2f 到 Rect2i 舍入
- C++ 中的舍入函数
- 舍入 QDecDouble 值,精度最多为两个字符
- 将大 int 转换为浮点数,而不舍入 c++
- 舍入错误检测
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- 将整数舍入到另一个整数的最接近的倍数
- Sizeof 舍入到对齐方式,但编译器仍将对象放在剩余的字节中
- 避免将 Int 转换为双重类型转换舍入
- 浮点数学运算后舍入不一致
- 浮动到绳子而无需舍入
- 实现整数除法向上舍入的正确方法是什么?
- 不带逻辑运算符的舍入整数除法
- 使用整数除法减少舍入错误