Meaning of "%" operation in C# for the numeric type double
The modulus operator works on floating point values in the same way as it does for integers. So consider a simple example:
4.5 % 2.1
Now, 4.5/2.1 is approximately equal to 2.142857
So, the integer part of the division is 2. Subtract 2*2.1 from 4.5 and you have the remainer, 0.3.
Of course, this process is subject to floating point representability issues so beware – you may see unexpected results. For example, see this question asked here on Stack Overflow: Floating Point Arithmetic - Modulo Operator on Double Type
Is a % b always equivalent to a - b*Math.Round(a/b)?
No it is not. Here is a simple counter example:
static double f(double a, double b)
{
return a - b * Math.Round(a / b);
}
static void Main(string[] args)
{
Console.WriteLine(1.9 % 1.0);
Console.WriteLine(f(1.9, 1.0));
Console.ReadLine();
}
As to the precise details of how the modulus operator is specified you need to refer to the C# specification – earlNameless's answer gives you a link to that.
It is my understanding that a % b
is essentially equivalent, modulo floating point precision, to a - b*Math.Truncate(a/b)
.
From C# Language Specifications page 200:
Floating-point remainder:
float operator %(float x, float y);
double operator %(double x, double y);
The following table lists the results of all possible combinations of nonzero finite values, zeros, infinities, and NaN’s. In the table, x and y are positive finite values. z is the result of x % y and is computed as x – n * y, rounded to the nearest representable value, where n is the largest integer that is less than or equal to x / y. This method of computing the remainder is analogous to that used for integer operands, but differs from the IEC 60559 definition (in which n is the integer closest to x / y).
From the MSDN page :
The modulus operator (%) computes the remainder after dividing its first operand by its second. All numeric types have predefined modulus operators.
And
Note the round-off errors associated with the double type.