Math.IEEERemainder返回负面结果.为什么?

Jef*_*rey 7 .net .net-2.0

除了标准的mod运算符之外,.net框架还包括Math.IEEERemainder(x,y).这个功能到底在做什么?我不明白这产生的负数.

例:

Math.IEEERemainder(0, 2) = 0
Math.IEEERemainder(1, 2) = 1
Math.IEEERemainder(2, 2) = 0
Math.IEEERemainder(3, 2) = -1
Run Code Online (Sandbox Code Playgroud)

use*_*116 8

如果您阅读System.Math.IEEERemainder的MSDN页面中给出的示例,您会注意到两个正数可以具有负余数.

回报价值

一个等于x - (y Q)的数字,其中Q是舍入到最接近整数的x/y的商(如果x/y落在两个整数之间,则返回偶数整数).

所以: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.

*/
Run Code Online (Sandbox Code Playgroud)

结语

实际的问题可能是,"为什么我们有两个剩余的操作?" 处理浮点数据时,您始终需要了解浮点标准.由于我们处于21世纪,大多数都是IEEE 754,我们很少有人担心VAX F_Float与IEEE 754.

C#标准状态,该余数运算符(第7.7.3)中,当施加到浮点参数,当施加到整数参数是类似于余运算符.也就是说,在整数和浮点余数运算中使用相同的数学公式1(对于与浮点表示相关联的拐角情况的附加考虑).

因此,如果您希望浮点数上的余数运算符合当前的IEEE 754舍入模式,建议使用Math.IEEERemainder.但是,如果您的使用对C#余数运算符产生的舍入的细微差异不是特别敏感,那么继续使用运算符.

  1. 给定:z = x%y,则z = x - (x/y)*y

  • IEEE 754舍入模式与“ IEEERemainder”操作或“%”操作均无关,因为两者都是精确的。精确表示无论舍入模式如何,结果都是相同的。它们之间的区别在于整数商的基本概念。IEEERemainder将数学商四舍五入到最接近的整数,以得到x-q * y中的q。 (2认同)