0

I wrote a simple function and would like to get know the assert macro in use. When I test the function (moving_hysteresis) after the sixth assert function I get an abort and I could not find out why. The moving_hysteresis() function follows:

float moving_hysteresis(float Delta,float temp)
{    
float delta=Delta;
float temp_min=ZERO;
float temp_max=delta;
float result;

if(temp<=temp_max)
    {
        if(temp>=temp_min)
            {
                result=temp;
                return result;
            }
        else
            {
                result=temp+delta;
                return result;
            }
    }
else
    {
        result=temp-delta;
        return  result;
    }
 }

If I try to test this with

 assert(moving_hsysteresis(5.00,-5.01)==(float)-0.01);

I get an assertion and I could not find out why... For example, if I try to test this with

assert(moving_hsysteresis(5.00,-2.36)==(float)2.64); 

it works correctly. Somebody have any idea?

Jens
  • 69,818
  • 15
  • 125
  • 179

2 Answers2

2

If you compile the following code:

#include <stdio.h>
int main() {
    float a=5.00;
    float b=5.01;
    float c=0.01;
    printf("%.25f",a-b+c);
}

The value should be mathematically zero, but floating-point errors mean that the result will not be precisely zero. On my system this prints out -0.0000002291053533554077148.

For this reason, testing floats for inequality typically checks to within a small elipson instead of testing for exact inequality.

rlee827
  • 1,853
  • 2
  • 13
  • 32
0

Your first assertion works because the difference is just too small for the precision to work (Floating point precision is limited).

That's why your second assertion works.

gsamaras
  • 71,951
  • 46
  • 188
  • 305