Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

.net - Math.IEEERemainder returns negative results. Why?

The .net framework includes Math.IEEERemainder(x, y) in addition to the standard mod operator. What is this function really doing? I dont understand the negative numbers that this produces.

Example:

Math.IEEERemainder(0, 2) = 0
Math.IEEERemainder(1, 2) = 1
Math.IEEERemainder(2, 2) = 0
Math.IEEERemainder(3, 2) = -1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

  1. Given: z = x % y, then z = x - (x / y) * y

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...