what is the best way to avoid negative zero in out

2019-01-20 08:33发布

问题:

As in this question is said, there is some differences between negative and positive zero in floating point numbers. I know it's because of some important reasons. what I want to know is a short code to avoid negative zero in output.

for example in the following code:

cout << fixed << setprecision(3);
cout << (-0.0001) << endl;

"-0.000" is printed. but I want "0.000".

Note all other negative numbers (e.g. -0.001) should still be printed with the minus sign preceding them, so simply * -1 will not work.

回答1:

Try depending on your precision.

cout << ((abs(ans) < 0.0005)? 0.000: ans) << endl;



回答2:

How about:

cout << (value == 0.0 ? abs(value) : value)  << endl;


回答3:

If you care about arbitrary precision, as opposed to just a fixed one at 3, you'll need a small bit of work. Basically, you'll have to do a pre-check before the cout to see if the number will get formatted in a way you don't like.

You need to find the order of magnitude of the number to see if it the imprecise digits will be lost, leaving only the sign bit.

You can do this using the base 10 logarithm of the absolute value of the number. If negative of result is greater than the precision you have set, the number will show in a way you don't want.

log10 of 0.0001 is -4.

negative of (-4) is 4.

4 > 3 (the arbitrary precision) Thus the value will show up unhappily.

In very bad pseudocode:

float iHateNegativeZeros(float theFloat, int precision)
{
   if((theFloat < 0.0f) &&
      (-log10(abs(theFloat)) > precision))
   {
     return -theFloat;
   }
   else
   {  
     return theFloat;
   }
}