Math.IEEERemainder返回否定结果。为什么?
时间:2020-03-06 14:58:48 来源:igfitidea点击:
.net框架除标准mod运算符外,还包括Math.IEEERemainder(x,y)。此功能实际上在做什么?我不明白这产生的负数。
例子:
Math.IEEERemainder(0, 2) = 0 Math.IEEERemainder(1, 2) = 1 Math.IEEERemainder(2, 2) = 0 Math.IEEERemainder(3, 2) = -1
解决方案
如果我们阅读System.Math.IEEERemainder的MSDN页面上给出的示例,我们会注意到两个正数可以有一个负的余数。
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).
因此: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. */
结语
实际的问题可能是:"为什么我们要进行两个余数运算?"处理时
浮点数据,我们始终需要了解自己的浮点标准。由于我们处在21世纪,因此大多数内容都在IEEE 754上,而我们中很少有人担心说VAX F_Float与IEEE 754的关系。
Cstandard指出,余数运算符(第7.7.3节)应用于浮点参数时,类似于余数运算符应用于整数参数时。也就是说,在整数和浮点余数运算中都使用了相同的数学公式1(还考虑了与浮点表示法关联的边角情况)。
因此,如果我们希望对浮点数的余数运算符合当前的IEEE 754舍入模式,则建议使用Math.IEEERemainder。但是,如果使用方式对Cremainder运算符产生的舍入的细微差别不特别敏感,请继续使用该运算符。
- 给定:z = x%y,则z = x-(x / y)* y