如何在浮点计算中得到-0结果并与C#中的+0区分开来?
MSDN 文档提到 double 类型包含负零。 但是,-1.0 / double.PositiveInfinity
和 -double.Epsilon / 2
似乎都返回正常的 0(并且比较等于它)。 我怎样才能得到-0?
The MSDN documentation mentions that double
type includes negative zero. However, both -1.0 / double.PositiveInfinity
and -double.Epsilon / 2
appear to return normal 0 (and compare equal to it). How can I get -0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个在不检查位的情况下区分两者的实际示例。 MSDN 链接此处和此处 帮助我构建了这个示例。
输出:
请注意,对于比较、输出等,-0 和 0 看起来都是相同的。但是如果你用 1 除以它们,你会得到 -Infinity 或 Infinity,具体取决于你有哪个零。
Here is a practical example of differentiating between the two without examining the bits. MSDN links here and here assisted me in constructing this example.
Output:
Take note that -0 and 0 both look the same for comparisons, output, etc. But if you divide 1 by them, you get a -Infinity or Infinity, depending on which zero you have.
负零与数字以二进制存储的方式有关,而不是数学计算中任何实际可实现的结果。
在浮点存储中,最高位通常用于表示符号。 这留下了 31 位数据(以 32 位浮点值表示),因此实际上有两种零表示形式。
00000000 00000000 00000000 00000000
或者
00000000 00000000 00000000 00000001
两者均表示零,但符号位设置为负数。
当然,当您增加最大可能的正数时,通常会发生这种情况,它会溢出回负零。
然而,在 .net 中,我认为默认情况下该类型会进行溢出检查,并会抛出异常而不是让您溢出,因此真正存档此值的唯一方法是直接设置它。 此外,-0 应该始终等于 +0。
Wikipeida 上有更多相关信息
Negative zero is to do with the way that the number is stored in binary, not any real achievable result from a mathematical calculation.
In floating point storage, the topmost bit is often used to denote sign. This leaves 31 bits for data (in a 32bit floating point value) so there are actually two representations for zero.
00000000 00000000 00000000 00000000
Or
00000000 00000000 00000000 00000001
Both represent zero, but one with the sign bit set to negative.
Naturally, this would normally occur when you incremented the highest possible positive number, it would overflow back to negative zero.
In .net however I think by default the type does overflow checks and will throw an exception rather than let you overflow, so the only way to really archive this value is by setting it directly. Also, -0 should always compare equal to +0.
There is more about it on Wikipeida
一种方法是使用 BitConverter.GetBytes。 如果检查字节,您将看到该值的符号位实际上已设置,表明其为负值。
One way is to use the BitConverter.GetBytes. If you check the bytes, you will see that the sign bit for the value is actually set indicating that its negative.
尝试这个。 如果
pz
是正零并且nz
是负零:我从 ECMA C# 规范。
您可以通过将任何正数除以负无穷大来获得负零:
Try this. If
pz
is positive zero andnz
is negative zero:I got this from ECMA C# specification.
You can obtain negative zero by dividing any positive number by negative infinity:
检查后,我发现
-1.0 / double.PositiveInfinity
确实返回-0。 事实上,1.0 / (-1.0 / double.PositiveInfinity)
返回-infinity
。After checking, I see that
-1.0 / double.PositiveInfinity
does return -0. Indeed,1.0 / (-1.0 / double.PositiveInfinity)
returns-infinity
.