Numerics BigInteger.Remainder (Mod) 不适用于负除数

huangapple go评论66阅读模式
英文:

Numerics BigInteger.Remainder (Mod) doesn't work with negative divisors

问题

考虑以下方程:

10 %  3 =  1
10 % -3 = -2

10001 %  30 =  11
10001 % -30 = -19

C#的System.Numerics.BigInteger似乎对负除数产生正结果,就好像在计算中使用了Abs(divisor)之类的东西;例如:

10 % -3

BigInteger left = 10;
BigInteger right = -3;

Console.WriteLine(left % right); // 1,但应该是 -2

10001 % -30

BigInteger left = 10001;
BigInteger right = -30;

Console.WriteLine(left % right); // 11,但应该是 -19

为什么会这样?这是一个错误吗?

英文:

Consider the following equations:

10 %  3 =  1
10 % -3 = -2

10001 %  30 =  11
10001 % -30 = -19

C#'s System.Numerics.BigInteger Seems to produce positive results for negative divisors, as if something like Abs(divisor) has been used in the calculation; for example:

10 % -3

BigInteger left = 10;
BigInteger right = -3;

Console.WriteLine(left % right); // 1, but should be -2

10001 % -30

BigInteger left = 10001;
BigInteger right = -30;

Console.WriteLine(left % right); // 11, but should be -19

Why is this? Is this a bug?

答案1

得分: 2

Modulus/remainder 操作在不同的编程语言中可以对负数操作数有不同的行为。

.NET 一贯遵循 BigInteger 文档 中指定的约定:

模数操作返回的值的符号取决于 dividend 的符号:如果 dividend 是正数,则模数操作返回正数结果;如果是负数,则模数操作返回负数结果。对于 BigInteger 值的模数操作行为与其他整数类型的模数操作相同。

因此,您应该在 intlong 等类型中看到相同的行为,但这可能与其他平台(例如 Wolfram Alpha)的行为不同。在 .NET 中与 Java 相同 - 来自 JLS remainder operator 文档

从这个规则可以得出,余数操作的结果只有在被除数为负数时才能为负数,只有在被除数为正数时才能为正数。此外,结果的大小始终小于除数的大小。

英文:

Modulus/remainder operations can have different behaviors with negative operands in different programming languages.

.NET consistently follows the convention specified in the BigInteger documentation:

> The sign of the value returned by the modulus operation depends on the sign of dividend: If dividend is positive, the modulus operation returns a positive result; if it is negative, the modulus operation returns a negative result. The behavior of the modulus operation with BigInteger values is identical to the modulus operation with other integral types.

So you should see the same behavior with int, long etc - but that may be different behavior to other platforms (e.g. Wolfram Alpha). It happens to be the same in .NET as in Java - from the JLS remainder operator docs:

> It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.

huangapple
  • 本文由 发表于 2023年6月1日 17:13:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定