Question

I am trying to create a histogram using GSL. I get a problem when I try to add to the histogram the value of the division 1470/100. This results in 14.69999999 and when added to the histogram it gets rounded to the lower bin. My question is how can i make 1470/100 result in 14.7 and not 14.69999? Thank you

Edit:

int minRange = 14;
double val;


val = minRange + j*0.05;


gsl_histogram_increment(hist, val);

When val is added to the histogram it is considered to be 14.65 instead of 14.7. (j is 14 in this case).

I solved the issue by adding 1e-6 to val. Thank you for the help

Was it helpful?

Solution

This is a floating point precision issue. A good way to solve is to set the histrogram points just off the integral values, e.g. 15 - e where e is of the order 10-6.

OTHER TIPS

Yes,

Adding 1e-6 usually works, but in general you have to be more careful when truncating float.

This blog explain all the problems you can face if you want to round float numbers (and also the pitfalls of naive solutions). It also suggest the following more robust implementation of "adding 1e-6"

 float myround(float f)
 {
      if (f >= 0x1.0p23) return f;
      return (float) (unsigned int) (f + 0.49999997f);
 }

You can test that myround(0.49999997) = 0 and myround(0.49999999) = 1 .

So I would read this blog first before calling this question completely solved!

Another point is that c++11 has a new function called std::round which returns the nearest integer so you can also implement rounding by comparing std::abs(x - std::round(x)) < epsilon, where epsilon is your target. Again this is a naive implementation that is not as robust as myround (which you need to adapt to double).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top