Math.IEEERemainder(x,y)是否等同于x%y?

19

Math.IEEERemainder(x,y)x%y 两者之间有什么区别吗?

2个回答

14
不,它们并不相等。MSDN 显示了取模和 IEEERemainder 所使用的不同公式,并展示了一个简短的示例程序来说明它们之间的差异。
IEEERemainder = dividend - (divisor * Math.Round(dividend / divisor))

Modulus = (Math.Abs(dividend) - (Math.Abs(divisor) * 
      (Math.Floor(Math.Abs(dividend) / Math.Abs(divisor))))) * 
      Math.Sign(dividend)

以下是一些不同/相同输出的示例(摘自MSDN):

                         IEEERemainder              Modulus
   3 / 2 =                          -1                    1
   4 / 2 =                           0                    0
   10 / 3 =                          1                    1
   11 / 3 =                         -1                    2
   27 / 4 =                         -1                    3
   28 / 5 =                         -2                    3
   17.8 / 4 =                      1.8                  1.8
   17.8 / 4.1 =                    1.4                  1.4
   -16.3 / 4.1 =    0.0999999999999979                   -4
   17.8 / -4.1 =                   1.4                  1.4
   -17.8 / -4.1 =                 -1.4                 -1.4

同时也可以看看这篇由sixlettervariables在类似问题上提供的answer


6
我在想,我为什么要那些结果?11 / 3= -1?很明显这里的模数是2。但是在什么情况下我会需要-1 - Royi Namir

3
不,它们不相同;请参阅文档
以下是源代码:
    public static double IEEERemainder(double x, double y) { 
        double regularMod = x % y;
        if (Double.IsNaN(regularMod)) { 
            return Double.NaN;
        }
        if (regularMod == 0) {
            if (Double.IsNegative(x)) { 
                return Double.NegativeZero;
            } 
        } 
        double alternativeResult;
        alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x)); 
        if (Math.Abs(alternativeResult) == Math.Abs(regularMod)) {
            double divisionResult = x/y;
            double roundedResult = Math.Round(divisionResult);
            if (Math.Abs(roundedResult) > Math.Abs(divisionResult)) { 
                return alternativeResult;
            } 
            else { 
                return regularMod;
            } 
        }
        if (Math.Abs(alternativeResult) < Math.Abs(regularMod)) {
            return alternativeResult;
        } 
        else {
            return regularMod; 
        } 
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接