Discussion to talk about software related topics only.
SeeCwriter
Posts: 630 Joined: Mon May 12, 2008 10:55 am
Post
by SeeCwriter » Wed Aug 12, 2020 1:37 pm
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.
pbreed
Posts: 1088 Joined: Thu Apr 24, 2008 3:58 pm
Post
by pbreed » Thu Aug 13, 2020 9:35 am
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: 630 Joined: Mon May 12, 2008 10:55 am
Post
by SeeCwriter » Thu Aug 13, 2020 9:46 am
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: 630 Joined: Mon May 12, 2008 10:55 am
Post
by SeeCwriter » Thu Aug 13, 2020 10:05 am
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
pbreed
Posts: 1088 Joined: Thu Apr 24, 2008 3:58 pm
Post
by pbreed » Thu Aug 13, 2020 11:13 am
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: 630 Joined: Mon May 12, 2008 10:55 am
Post
by SeeCwriter » Thu Aug 13, 2020 12:40 pm
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 );
}