java - 为什么 Ruby 和 Python 长除法与 GMP 和 Java BigInteger 不同?

标签 java python ruby gmp bignum

我正在开发一个大整数类(教学目的),并且我一直在使用 Ruby 生成测试用例。我的类(class)在以下测试中失败:

a = -48197174570431531987668852939807674377435188974148779416366905274642031729688518691
b = 4322669160730708444058642850762359547515258361061655693150034467061
a / b = -11149864303351921    # Ruby answer

我在代码中找不到错误,因此我尝试使用其他工具验证结果,结果令人惊讶:o。

GMP、Java BigInteger 和我的类与此结果一致:

11149864303351920
-11149864303351920

但是 Ruby 和 Python 与此不谋而合:

-11149864303351921
11149864303351920

有人可以解释一下为什么会出现这种行为吗?请。

最佳答案

当整数除法的参数不都是正数时,必须决定对余数的商和符号进行舍入。 GMP 支持下限除法 (f_div...)、上限除法 (c_div...) 和截断除法 (t_div...)。

使用gmpy2通过Python访问GMP,

>>> import gmpy2
>>> a = -48197174570431531987668852939807674377435188974148779416366905274642031729688518691
>>> b = 4322669160730708444058642850762359547515258361061655693150034467061
>>> gmpy2.f_divmod(a,b)
(mpz(-11149864303351921), mpz(1542354793066875276328139562907995977816446564586050094773477055490))
>>> gmpy2.c_divmod(a,b)
(mpz(-11149864303351920), mpz(-2780314367663833167730503287854363569698811796475605598376557411571))
>>> gmpy2.t_divmod(a,b)
(mpz(-11149864303351920), mpz(-2780314367663833167730503287854363569698811796475605598376557411571))
>>> help(gmpy2.f_divmod)
f_divmod(x, y) -> (quotient, remainder)

Return the quotient and remainder of x divided by y. The quotient
is rounded towards -Inf (floor rounding) and the remainder will
have the same sign as y. x and y must be integers.

>>> help(gmpy2.c_divmod)
c_divmod(x, y) -> (quotient, remainder)

Return the quotient and remainder of x divided by y. The quotient
is rounded towards +Inf (ceiling rounding) and the remainder will
have the opposite sign of y. x and y must be integers.

>>> help(gmpy2.t_divmod)
t_divmod(x, y) -> (quotient, remainder)

Return the quotient and remainder of x divided by y. The quotient
is rounded towards zero (truncation) and the remainder will have
the same sign as x. x and y must be integers.

关于java - 为什么 Ruby 和 Python 长除法与 GMP 和 Java BigInteger 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18479510/

相关文章:

Python - 从文件填充数组,避免最后断行

android - Ruboto水平进度条?

ruby-on-rails - Bundler::RubyVersionMismatch: 你的 Ruby 版本是 1.9.3,但是你的 Gemfile 指定了 2.0.0

java - 在 Java 中创建对象数组时遇到问题

java - 改变方向 5 次后内存不足

python - 从绘图破折号中的代码中单击按钮

python - 如何监控 celery 中的一组任务?

javascript - 取消注释 jquery 如何导致 rails 服务器的工作?

java - 如何处理所有资源的无法识别的属性异常

java - 将数据传递到查询中,而不是更新