How to get rid of -0 in C ++

I am writing a program in which some operations on a floating point number are performed. After debugging the program, I found out that for a specific test case the value of variable equals -2.38418579e-07 . Now I have cout accuracy set to 2 digits after decimal. Therefore, when I print it, it prints it as -0.00.

However, I would like the result to be 0.00 instead of -0.00. I tried various if conditions for the value of the variable. However, they do not help. Can anyone suggest how to get rid of -0.00 in C ++

+6
source share
3 answers

First, you must define the tolerance number as a threshold where the absolute value of any floating point number below this threshold will be considered zero. For example, you can define this threshold as:

 #define zero 1e-6 

Then you can use the following construction to β€œfilter” floating point numbers:

 template<typename T> std::enable_if_t<std::is_floating_point<T>::value, T> sanitize(T &&num) { return std::abs(num) < zero? T{} : num; } 

Live demo

Note that I use SFINAE so that the sanitize function accepts only floating-point numbers as input.

+3
source

I would like the result to be 0.00 instead of -0.00

I like the other answers better. But in a crunch, you can always use brute force ... (are you sure you can ignore the actual results?)

 std::string rslt; { std::stringstream ss; ss << variable; // use same formatting as in your example size_t minusSignIndx = ss.str().find("-0.00"); if (minusSignIndx != std::string::npos) rslt = " 0.00"; // found the nasty, ignore it else rslt = ss.str(); // not nasty, use it } //... use rslt 
0
source

The problem is that every floating point in a certain interval [low, -0.0] will print "-0.00".

So you should find low:

  • so print (predecessor (low)) => "-0.01"
  • so print (low) => "-0.00"

Then you can write something like (nano-separation ...)

 double filter(double x) { double low = ... ; return (x < low) ? x : ((x > 0.0) ? x : 0.0) ; } 

If you have correctly rounded printf and control your arithmetic strictly IEEE754, corresponding to the corresponding compiler flags, the exact value low is the closest double - 1/200, greater than -1/200 (I write 1/200, and not -0.005, therefore what I'm talking about decimal value, not double)

What we have with correctly rounded sscanf ("- 0.005", "% lf", d): a double result is less than -1/200. I checked this with exact arithmetic, for example in Pharo Smalltalk:

 [-0.005 < (-1/200) and: [-0.005 successor > (-1/200)]] assert. 

His successor is greater than -1/200 (required, higher verification is just protection).

So you can write (note the <= low):

 double filter(double x) { double low = 0.005 ; return (x <= low) ? x : ((x > 0.0) ? x : 0.0) ; } 
0
source

All Articles