quotRem和divMod之间的区别何时有用? [英] When is the difference between quotRem and divMod useful?
问题描述
如果y,quot,rem,div和mod类
方法满足这些定律是
非零:
(x`quot` y)* y +(x`rem` y) == x
(x`div` y)* y +(x`mod` y)== x
quot
是整数除法将
截断为零,而div
$的结果b $ b被截断为负无穷。
例如:
前奏> (-12)``5
-2
前奏> (-12)`div` 5
-3
什么是一些例子
许多语言都有一个mod或%运算符,它给出了剩余的截断后向0分割;例如C,C ++和Java以及C#可能会说:
$ p $ ( - 11)/ 5 = -2
(-11)%5 = -1
5 *(( - 11)/ 5)+(-11)%5 = 5 *( - 2)+(-1)= - 11。
Haskell的 quot
和 rem
是为了模仿这种行为。我可以想象,在某些人为的情况下,与某些C程序的输出兼容可能是可取的。
Haskell的 div
和 mod
,随后是Python的/和%,遵循数学家(至少是数理论家)的惯例总是截断向下划分(而不是0 - 朝向负无穷),以便余数总是非负的。因此,在Python中,
( - 11)/ 5 = -3
(-11)%5 = 4
5 *(( - 11)/ 5)+( - 11)%5 = 5 *( - 3)+ 4 = -11。
Haskell的 div
和 mod
遵循此行为。
From the haskell report:
The quot, rem, div, and mod class methods satisfy these laws if y is non-zero:
(x `quot` y)*y + (x `rem` y) == x (x `div` y)*y + (x `mod` y) == x
quot
is integer division truncated toward zero, while the result ofdiv
is truncated toward negative infinity.
For example:
Prelude> (-12) `quot` 5
-2
Prelude> (-12) `div` 5
-3
What are some examples of where the difference between how the result is truncated matters?
Many languages have a "mod" or "%" operator that gives the remainder after division with truncation towards 0; for example C, C++, and Java, and probably C#, would say:
(-11)/5 = -2
(-11)%5 = -1
5*((-11)/5) + (-11)%5 = 5*(-2) + (-1) = -11.
Haskell's quot
and rem
are intended to imitate this behaviour. I can imagine compatibility with the output of some C program might be desirable in some contrived situation.
Haskell's div
and mod
, and subsequently Python's / and %, follow the convention of mathematicians (at least number-theorists) in always truncating down division (not towards 0 -- towards negative infinity) so that the remainder is always nonnegative. Thus in Python,
(-11)/5 = -3
(-11)%5 = 4
5*((-11)/5) + (-11)%5 = 5*(-3) + 4 = -11.
Haskell's div
and mod
follow this behaviour.
这篇关于quotRem和divMod之间的区别何时有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!