除了标准的 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
最佳答案
如果您阅读 System.Math.IEEERemainder's MSDN page 中给出的示例,您会注意到两个正数可以有负余数。
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。
C# standard声明余数运算符(第 7.7.3 节)应用于浮点参数时,类似于应用于整数参数时的余数运算符。也就是说,在整数和浮点余数运算中使用相同的数学公式1(对与浮点表示相关的极端情况有额外的考虑)。
因此,如果您希望对浮点数的余数运算符合您当前的 IEEE 754 舍入模式,建议使用 Math.IEEE余数 .但是,如果您的用法对 C# 余数运算符产生的舍入的细微差异不是特别敏感,请继续使用该运算符。
关于.net - Math.IEEERemainder 返回否定结果。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/158120/