忍者ブログ
[PR]
×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

【2024年04月24日09:19 】 |
負の除算・・・
手廻計算器には色々な計算テクニックが詰まってる^^
割り算には引き戻し法引き放し法などが用いられるが・・・

その計算の正誤を判定するには検算をする
割り算の検算とは・・・

 商*除数+余=被除数
 余の絶対値<除数の絶対値

この2つの条件を満たしているとき
この除算は正しい・・・

上の条件は除数・被除数ともに正のとき
答えは唯一となるが・・・
負の数が入ると・・・^^;

たとえば-5/3の場合

商=-1 余=-2 の場合と・・・
商=-2 余= 1 の場合が・・・

どちらも上の2つの条件を満たし正しい・・・
どちらの計算結果になるかは実装による・・・^^;

最近では・・・

 商*除数の絶対値<=被除数の絶対値

この条件を加えて計算結果が唯一になるように
言語仕様を決めている言語もある

Javaの場合・・・

Java言語仕様第3版
(The Java Language Specification, Third Edition)
15.17.2 Division Operatorに・・・

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d・q||n|; moreover, q is positive when |n||d| and n and d have the same sign, but q is negative when |n||d| and n and d have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is -1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is 0, then an ArithmeticException is thrown.

百聞は一見にしかずということで
Java6update3で実行してみる・・・
-5 % 3 = -2
5 % -3 = 2
-5 % -3 = -2
-2 % 3 = -2
2 % -3 = 2
-2 % -3 = -2


となった
ちなみにExcel2003では・・・
-5 mod 3 = 1
5 mod -3 = -1
-5 mod -3 = -2
-2 mod 3 = 1
2 mod -3 = -1
-2 mod -3 = -2


となった
PR
【2007年12月02日07:30 】 | Java | コメント(0) | トラックバック()
<<mod と remainder・・・ | ホーム |今日は・・・>>
コメント
コメントの投稿













トラックバック
トラックバックURL

前ページ| ホーム |次ページ

忍者ブログ [PR]