.net - Math.IEEERemainder 返回否定结果。为什么?

标签 .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

最佳答案

如果您阅读 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# 余数运算符产生的舍入的细微差异不是特别敏感,请继续使用该运算符。
  • 给定:z = x % y,那么 z = x - (x/y) * y
  • 关于.net - Math.IEEERemainder 返回否定结果。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/158120/

    相关文章:

    .net - 安装包 SignalR 导致无法找到包 'SignalR'

    visual-studio - 'Update Web Reference"出现问题

    c# - .NET 2 中资源的奇怪问题

    .net 2.0安全配置

    c# - 如何判断操作系统是 Windows XP 还是更高版本?

    c++ - .NET 2.0 + C++ 的加密算法/库

    c# - 什么时候函数内的局部变量*实际上*被分配

    c# - 如何在 2 个 .Net 应用程序之间交换对象

    c# - Windows 事件日志中的 LdapConnection.SendRequest() 问题

    c# - 如何以通用方式编写以下逻辑?