Recently I discovered that C#’s operator % is applicable to double. Tried some things out, and after all came up with this test:
class Program
{
static void test(double a, double b)
{
if (a % b != a - b * Math.Truncate(a / b))
{
Console.WriteLine(a + ", " + b);
}
}
static void Main(string[] args)
{
test(2.5, 7);
test(-6.7, -3);
test(8.7, 4);
//...
}
}
Everything in this test works.
Is a % b always equivalent to a - b*Math.Round(a/b)? If not, please explain to me how this operator really works.
EDIT: Answering to James L, I understand that this is a modulo operator and everything. I’m curious only about how it works with double, integers I understand.
The modulus operator works on floating point values in the same way as it does for integers. So consider a simple example:
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
No it is not. Here is a simple counter example:
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 % bis essentially equivalent, modulo floating point precision, toa - b*Math.Truncate(a/b).