rid
rid

Reputation: 63442

Floating point value of 0 greater than 0

I can't reproduce this with a simple program, but somewhere in my program I have something like:

float e = f(...);
if (e > 0.0f) {
    ...

printf("%f", e) shows that e is 0.000000, yet e > 0.0f is true... So is e > 0 and e > 0.0. What am I missing?

Upvotes: 3

Views: 3077

Answers (4)

Lawrence Woodman
Lawrence Woodman

Reputation: 1444

The problem is that the floating point value is greater than 0, but less than the precision that printf uses to print floating point numbers with %f. You can use %e or %g for better results as illustrated with the following program.

#include <math.h>
#include <stdio.h>

void main(void)
{
  int i;
  float e;

  for (i = 1; i < 64; i++) {
    printf("Decimal places: %d\n", i);

    e = 1.0 / pow(10, i);

    if (e > 0.0f) {
      printf("Value displayed with %%e: %e > 0.0f\n", e);
      printf("Value displayed with %%f: %f > 0.0f\n", e);
      printf("Value displayed with %%g: %g > 0.0f\n\n", e);

    }
  }
}

You will need to compile this with the maths library. For gcc use: -lm

Upvotes: 3

dan1111
dan1111

Reputation: 6566

Your problem is that e is actually not zero. It has some tiny value in it, but that gets hidden because %f converts to decimal, losing precision. Use printf("%e",e) instead as your debug statement, and you will see that there is a nonzero value in there.

Upvotes: 0

Christian Rau
Christian Rau

Reputation: 45948

The fact that printf("%f", e) shows it to be zero doesn't mean anything, because printf rounds the value both to decimal floating point and to the precision of the output, so very small numbers larger than 0 are likely to be put out as 0.

Try printf("%e", e) or printf("%.17f", e) and see what happens.

Upvotes: 3

Aki Suihkonen
Aki Suihkonen

Reputation: 20027

The floating point value is larger than zero, but less than 1e-7. It's printing issue. Use scientific notation printf("%e", value); or "%g" for shortest notation.

Upvotes: 5

Related Questions