Testing floats

Discussion to talk about software related topics only.
Post Reply
SeeCwriter
Posts: 606
Joined: Mon May 12, 2008 10:55 am

Testing floats

Post 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.
User avatar
pbreed
Posts: 1080
Joined: Thu Apr 24, 2008 3:58 pm

Re: Testing floats

Post 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.
SeeCwriter
Posts: 606
Joined: Mon May 12, 2008 10:55 am

Re: Testing floats

Post 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?
SeeCwriter
Posts: 606
Joined: Mon May 12, 2008 10:55 am

Re: Testing floats

Post 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
User avatar
pbreed
Posts: 1080
Joined: Thu Apr 24, 2008 3:58 pm

Re: Testing floats

Post 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..
SeeCwriter
Posts: 606
Joined: Mon May 12, 2008 10:55 am

Re: Testing floats

Post 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 );
}
Post Reply