2009-12-28 14 views

Antwort

12

Nein, sie sind nicht gleichwertig. MSDN zeigt die verschiedenen Formeln für Modulo verwendet und für IEEERemainder und hat ein kurzes Beispielprogramm, die Unterschiede aufweist:

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) 

Einige Beispiele, in denen sie unterschiedlichen/identischen Ausgang (aus MSDN) haben:

      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 

Siehe auch dieses gute answer von sixlettervariables zu einer ähnlichen Frage.

+1

Ich frage mich nur - Warum in aller Welt möchte ich diese Ergebnisse? '11/3 = -1'? klar ist der Modul hier 2. Aber auf welchen Szenarien würde ich '-1' wollen? –

+0

@RoyiNamir Sie haben eine Antwort hier: http://StackOverflow.com/a/27378075/200443 – Maxence

2

Nein, sie sind nicht gleich; siehe die documentation.

Hier ist die Quelle:

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