1

私はBig Integerクラス(教訓的な目的)を開発しており、Rubyを使用してテストケースを生成しています。私のクラスは次のテストで失敗します:

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

コードにバグが見つからなかったので、他のツールで結果を検証しようとしましたが、驚きました:o.

GMP、Java BigInteger、および私のクラスは、次の結果と一致します。

11149864303351920
-11149864303351920

しかし、Ruby と Python はこれと一致します。

-11149864303351921
11149864303351920

誰かがこの動作の理由を説明できますか?、お願いします。

4

2 に答える 2

1

整数除算の引数が両方とも正ではない場合、商の丸めと剰余の符号について決定を下す必要があります。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.
于 2013-08-28T04:50:50.167 に答える