boost::multiprecision::cpp_int:我想确认两个正cpp_int的除法截断为零

boost::multiprecision::cpp_int: I would like to confirm that division of two positive cpp_int's truncates towards zero

本文关键字:cpp int 除法 两个 multiprecision 确认 boost      更新时间:2023-10-16

我用boost::multiprecision::cpp_int,我找不到两个正的cpp_int除向0截断的证实;例如,

boost::multiprecision::cpp_int A {11};
boost::multiprecision::cpp_int B {4};
boost::multiprecision::cpp_int C = A / B; // 2, right?

在c++中,integer类型中的AB,标准要求对0进行截断,使答案为C = 2

我假设cpp_int的工作方式相同- cpp_int的答案也是2

然而,我找不到这个假设的证实。我也在boost::multiprecision::cpp_int的源代码中寻找了几分钟,但我没有发现确认行为是微不足道的。

我想确认boost::multiprecision::cpp_int在除两个正整数时按预期工作-即,它将结果截断到0

谢谢!

整数除法或模运算符的主要选项是向零舍入或向负无穷舍入。虽然在数学上趋向负无穷更正确,但C/c++趋向零。当被除数和除数有不同的符号时,这会影响除数或取模。向零舍入表示模数的结果与被除数的符号相同(或零),向负无穷舍入表示模数的结果与被除数的符号相同(或零)。

不涉及截断

截断假定存在一个中间的非整型结果。事实并非如此。唯一为cpp_int(或任何其他多精度整数)定义的除法操作包括整数除法:

  • divide_qr -设置q = x / yr = x % y

    template <class Backend, expression_template_option ExpressionTemplates>
        void divide_qr(const number-or-expression-template-type& x, const number-or-expression-template-type& y,
        number<Backend, ExpressionTemplates>& q, number<Backend, ExpressionTemplates>& r);
    
  • integer_modulus -返回x % val;

    template <class Integer>
    Integer integer_modulus(const number-or-expression-template-type& x, Integer val);
    

除了整数除法这个定义良好的概念,并且出现在所有主流编程语言中,否则就没有任何意义,因为(至少对于正整数*¹*)

x == (q*y) + r

应为真


¹ IIRC混合符号模在c++中未定义;除非你能在代码/文档

中找到它们,否则我不会期望在这里得到保证。