c# - 为什么 double.IsNegative(double.NaN) 返回 true?
问题描述
为什么double.IsNegative(double.NaN)
意外返回true
而按预期double.NaN < 0
返回false
?
解决方案
好吧,根据参考来源,double.IsNegative
只需检查最重要的位:
[Pure]
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static bool IsNegative(double d) {
return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000;
}
如果设置了double.NaN
最重要的位:
11111111 11111000 00000000 00000000 00000000 00000000 00000000 00000000
|| || |
|<- Exp -><- Mantissa ->
Sign
这就是为什么double.IsNegative
返回true
当我们使用 put<
或>
FPU命令时,这些命令都知道指数是一种特殊的浮点值,应该以特殊的方式处理。
同样的图片与Single.NaN
.
请注意,我们可以构造另一个奇怪的值,负零:
10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
|| || |
|<- Exp -><- Mantissa ->
Sign
敬请期待:
double negativeZero = BitConverter.ToDouble(new byte[] {
0, 0, 0, 0, 0, 0, 0, 128
});
Console.WriteLine(negativeZero == 0 ? "Zero" : "???");
Console.WriteLine(double.IsNegative(negativeZero) ? "Negative" : "???");
推荐阅读
- java - 如何在 SEservice 中使用 Executor (Open Mobile API for Android 9.0)
- asp.net-web-api - 为 ASP.Net Core ApiController 创建 WSDL
- vue.js - “未定义模板或渲染函数”错误
- android - 如何修复 NativeScript 错误:找不到模块:“nativescript-pager/angular”
- mysql - 使用 MySQL 连接表
- python - 你能解释一下每次迭代时 keras 的输出吗?
- bash - Shell 程序,for 循环出错。未使用的变量
- git - S3 版本控制与 Git 有何不同?
- python - 计算字符串中尾随的换行符
- view - Lotus @-formula - 是否可以为视图创建动态选择公式?