Faken
Faken

Reputation: 11822

How do i prevent or deal with -0 values?

My program seems to be producing some -0 values in place of values that should be 0. How do i stop my program from outputting these values?

Is it as simple as checking if a value is equal to -0 and reassigning it a zero instead? Or is there a more elegant solution?

Upvotes: 0

Views: 878

Answers (3)

Francis
Francis

Reputation: 12008

Sounds like you are using floating numbers. The -0 should be in fact a very small negative number like -0.0000001 which was truncated by your printing function. You can examine this by a good debugger, or print the raw float/double as hex bytes.

You can make some compare and set it to zero. (eg, if (n<0 && n > -0.0001) n = 0;)

(edit) Maybe you are doing things like this:

#include <stdio.h>
#include <float.h>
#include <iostream>

int main()
{
    double d = -DBL_MIN;
    std::cout << std::fixed << d << std::endl;
    return 0;
}

// output: -0.000000

Maybe you can try to print out the real value inside your float / double. That is,

cout << *(__int64)&d; // if d is double
cout << *(__int)&f;   // if f is float

Printing that helps to understand what happened.

Upvotes: 0

Windows programmer
Windows programmer

Reputation: 8065

Since a tag says visual-c++, it seems you're running on Windows on an Intel or compatible chip, so integer values of -0 aren't possible. Maybe you have a floating point value that's negative but very close to 0, for example -0.000000000000009, and maybe you're printing it with only a few digits of precision, for example -0.00000. In this case you could do something like:

if (x > -0.0000001 && x <= 0) x = 0;

Of course you want to do it with more style than that, but that gives you an idea.

The main text of your question doesn't say Visual C++ or Windows or Intel. If you're running on a one's complement machine, integer values of -0 are possible. Normally -0 compares equal to +0, so the following code would normalize integer zeros:

if (y == 0) y = 0;  // This looks redundant but it turns a -0 into a +0

Upvotes: 1

Arthur Kalliokoski
Arthur Kalliokoski

Reputation: 1647

http://en.wikipedia.org/wiki/Signed_zero says: According to the IEEE 754 standard, negative zero and positive zero should compare as equal with the usual (numerical) comparison operators.

I'd investigate whether the variables could be cast to a 32 bit int (for float) or 64 bit int (for double) and see if they're equal to 0x8000...

Upvotes: 1

Related Questions