是否有一个原因,一些语言允许负模? [英] Is there a reason some languages allow a negative modulus?
问题描述
我很好奇这些语言(Java,C ...)这忽略模运算的数学定义。
I am curious about these languages (Java, C ...) which ignore mathematical definition of modulus operation.
这是在一个模块的操作返回负值(即,根据定义,应永诺返回一个正数)
What is the point of returning negative values in a module operation (that, by definition, should allways return a positive number)?
推荐答案
我怀疑其余运营商故意设计成具有这些语义,这我同意是不是非常有用。 (你怎能写,显示了平日周日,反日,反日,...,反周一的开天辟地之前日期的日历程序?)
I doubt that the remainder operator was deliberately designed to have those semantics, which I agree aren't very useful. (Would you ever write a calendar program that shows the weekdays Sunday, Anti-Saturday, Anti-Friday, ..., Anti-Monday for dates before the epoch?)
相反,负余数的方式整数除法的副作用被定义
Rather, negative remainders are a side effect of the way integer division is defined.
A rem B := A - (A div B) * B
如果 A DIV乙
定义为 TRUNC(A / B)
,你都会得到C的%
运营商。如果 A DIV乙
定义为楼(A / B)
,你得到Python的%
运营商。其他定义是可能的。
If A div B
is defined as trunc(A/B)
, you get C's %
operator. If A div B
is defined as floor(A/B)
, you get Python's %
operator. Other definitions are possible.
所以,真正的问题是:
,因为这是C那样被它的方式。
Because that's the way that C does it.
最初,C没有具体说明 /
应处理负数。它留给它的硬件。
Originally, C didn't specify how /
should handle negative numbers. It left it up to the hardware.
在实践中,每一个显著C实现使用了舍去除法,所以在1999年,这些语义被正式提出的C标准的一部分。
In practice, every significant C implementation used truncating division, so in 1999 these semantics were formally made a part of the C standard.
由于它更容易(=便宜)在无符号除法的条款实施。你刚才计算 ABS(A)DIV ABS(B)
和翻转的迹象,如果(A℃下)XOR(B&小于0)
。
Because it's easier (=cheaper) to implement in terms of unsigned division. You just calculate abs(A) div abs(B)
and flip the sign if (A < 0) xor (B < 0)
.
地板除法具有从商减去1,如果余数为非零的附加步骤。
Floored division has the additional step of subtracting 1 from the quotient if the remainder is nonzero.
这篇关于是否有一个原因,一些语言允许负模?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!