【问题标题】:Is Math.IEEERemainder(x,y) equivalent to x%y?Math.IEEERemainder(x,y) 是否等同于 x%y?
【发布时间】:2009-12-28 21:29:27
【问题描述】:

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

【问题讨论】:

    标签: .net


    【解决方案1】:

    不,它们不相等。 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

    【讨论】:

    • 我只是想知道 - 我到底为什么想要这些结果? 11 / 3= -1 ?显然这里的模数是 2。但是在什么情况下我想要-1
    【解决方案2】:

    不,它们不一样;见documentation

    来源:

        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; 
            } 
        }
    

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 2016-05-06
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多