Math.IEEERemainder returns negative results. Why?

前端 未结 1 1935
孤街浪徒
孤街浪徒 2020-12-18 01:15

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 t

相关标签:
1条回答
  • 2020-12-18 01:53

    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
    0 讨论(0)
提交回复
热议问题