If you read the example given at System.Math.IEEERemainder's MSDN page, you'll notice that two positive numbers can have a negative remainder.
Return Value
A number equal to x - (y Q), where Q is the quotient of x / y rounded to the nearest integer (if x / y falls halfway between two integers, the even integer is returned).
So: 3 - (2 * (round(3 / 2))) = -1
/*
...
Divide two double-precision floating-point values:
1) The IEEE remainder of 1.797693e+308/2.00 is 0.000000e+000
2) The IEEE remainder of 1.797693e+308/3.00 is -1.000000e+000
Note that two positive numbers can yield a negative remainder.
*/
Epilogue
The actual question could be, "Why do we have two remainder operations?" When dealing with
floating point data, you always need to be cognizant of your floating point standard. Since we're in the 21st century, most everything is on IEEE 754 and very few of us worry about say VAX F_Float versus IEEE 754.
The C# standard states that the remainder operator (Section 7.7.3), when applied to floating point arguments, is analogous to the remainder operator when applied to integer arguments. That is, the same mathematical formula1 is used (with additional considerations for corner cases associated with floating point representations) in both integer and floating point remainder operations.
Therefore, if you are looking to have your remainder operations on floating point numbers conform to your current IEEE 754 rounding modes, it is advisable to use Math.IEEERemainder. However, if your usage is not particularly sensitive to the subtle difference in rounding produced by the C# remainder operator, then continue using the operator.
- Given: z = x % y, then z = x - (x / y) * y
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…