Thread: Cycling variable, threshold

1. Cycling variable, threshold

Hi there,

I have a float called counter that goes from 0 to 31 and then back to 0. I want to be able to specify a number x (0-31) and a threshold th, and check if the number is within th units from the counter.

Sounds easy at first:
if( abs(x - counter) <= th )

But this doesn't work if x is close to 0 and counter is close to 31. I've thought about this for quite a while but can't seem to come up with a solution. Help would be greatly appreciated!

2. First of all the abs function has this prototype:
int abs(int j);
It aspects an int not a float.

Use one of this instead:

#include <math.h>

double fabs(double x);
float fabsf(float x);

3. Thanks ralu, I'm using a language very similar to C but which has an abs function that is overloaded for many types.
Code:
```Anyway, I found a solution:
if(abs(a - (ctr % 32)) <= threshold)
return true;
else
if(abs(32 + a - (ctr % 32)) <= threshold)
return true;
else
return false;```

Popular pages Recent additions