Page 1 of 1

Testing floats

Posted: Wed Aug 12, 2020 1:37 pm
by SeeCwriter
I have floating point variable that managed to get corrupted, and I'm unsuccessful in testing for that condition and I don't understand why.

The value output is -6785893894054400000000000000000000.0000

Isn't that value too long for a float?

Code: Select all

float fval;
...

if ( fval <= 0.0 || fval > 100.0 )
{
  puts("value out of range");  // Never get here!!
}
else
{
  printf( "%.4f", fval);
}
v2.9.2, MOD54415.

Re: Testing floats

Posted: Thu Aug 13, 2020 9:35 am
by pbreed
Single precision float can be

±3.4×10^38

Note that there aren't 38 significant digits, just it can have a value with 38 decimal digits of magnitude.

Re: Testing floats

Posted: Thu Aug 13, 2020 9:46 am
by SeeCwriter
Ok, but why doesn't the if statement detect that the value is less than zero? Also, my understanding of the IEEE-754 Floating Point Standard is that, if a value is smaller/less than the smallest (most negative) value a float can represent, that it underflows to zero. Why doesn't that happen and the if statement detect it?

Re: Testing floats

Posted: Thu Aug 13, 2020 10:05 am
by SeeCwriter
FYI, I also tried converting the float to a double, and still the if statement doesn't work.

Code: Select all

float fval;
...
double d = fval;
if ( d <= 0.0 || d > 100.0 )
{
   puts("Value out of range"); // Never gets here.
}
else
{
  printf( "%.4f", d );
}
Output: -6785893894054400000000000000000000.0000

Re: Testing floats

Posted: Thu Aug 13, 2020 11:13 am
by pbreed
Add some parenthesis in the if, the precidence looks correct, but....
With float and double propotion going on in the parser one is never 100% sure..

Re: Testing floats

Posted: Thu Aug 13, 2020 12:40 pm
by SeeCwriter
It turns out that if the float value is not valid, then converting it to a double will not help. I solved the problem this way:

Code: Select all

float fval;
...
if ( isnan(fval) || isinf(fval) || fval <= 0.0 || fval > 100.0 )
{
   puts("Value out of range");
}
else
{
  printf( "%.4f", d );
}