How to get the result -0 in floating point calculations and distinguish it from +0 in C #?

The MSDN documentation mentions that the double type contains a negative zero. However, both -1.0 / double.PositiveInfinity and -double.Epsilon / 2 seem to return a normal 0 (and compare with it). How can I get -0?

+6
floating-point c # zero
source share
5 answers

Here is a practical example of differentiating two without exploring bits. The MSDN links here and here have helped me build this example.

 static void Main(string[] args) { float a = 5 / float.NegativeInfinity; float b = 5 / float.PositiveInfinity; float c = 1 / a; float d = 1 / b; Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); } 

Output:

 0 0 -Infinity Infinity 

Note that -0 and 0 both look the same for comparison, output, etc. But if you divide them by 1, you get a value of -Infinity or Infinity, depending on which zero you have.

+16
source share

A negative zero is related to the way the number is stored in binary expression, and not some real achievable result from a mathematical calculation.

In floating point storage, the topmost bit is often used to indicate a sign. This gives 31 bits for data (in a 32-bit 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 a sign set to negative.

Naturally, this usually happens when you increase the maximum possible positive number, it overflows to a negative zero.

In .net, however, I think that by default the type does overflow checks and throws an exception rather than allowing you to overflow, so the only way to really archive this value is to set it directly. In addition, -0 must always be compared with +0.

This is said more on Wikipeida.

+3
source share

One way is to use BitConverter.GetBytes. If you check the bytes, you will see that the sign bit for the value is actually set, indicating its negative.

 byte[] zeroBytes = BitConverter.GetBytes(zero); byte[] negZeroBytes = BitConverter.GetBytes(negZero); bool sameBytes = zeroBytes[7] == negZeroBytes[7]; 
+2
source share

Try it. If pz positive zero and nz negative zero:

 Double.PositiveInfinity/pz => Double.PositiveInfinity Double.PositiveInfinity/nz => Double.NegativeInfinity 

I got this from the ECMA C # specification .

You can get a negative zero by dividing any positive number by negative infinity:

 10.0/Double.NegativeInfinity 
+2
source share

After checking, I see that -1.0 / double.PositiveInfinity returns -0. Indeed 1.0 / (-1.0 / double.PositiveInfinity) returns -infinity .

0
source share

All Articles