Home » programming » How to avoid flunctuations around a threshold

# How to avoid flunctuations around a threshold

I read the interesting post Checking fluctuating variables using thresholds, the smart way from tzikis. Unfortunately, for some reason I can not post a comment there.

The problem is how to avoid the problem of fluctuations around “soft” thresholds. My solution simply defines a tolerance parameter. If we are “almost” at the same interval as before, we change nothing.

By the way, the bisect module is nice.

```import bisect

TOLERANCE = 50
INTERVALS = list(range(0, 1024, 128))

def interval_length(i):
if i <= 0:
return 0
try:
length = INTERVALS[i] - INTERVALS[i - 1]
except IndexError:
length = 0

return length

def belong(a, current=0):
""" Always return the index of the right threshold of the interval. """
if  0 - TOLERANCE <= INTERVALS[current] - a <= interval_length(current) + TOLERANCE:
return current

return bisect.bisect_right(INTERVALS, a)

def main():
a = belong(127)
print(a)
a = belong(150, a)
print(a)
a = belong(179, a)
print(a)
a = belong(560, a)
print(a)
a = belong(123, a)
print(a)
a = belong(999, a)
print(a)

if __name__ == '__main__':
print(INTERVALS)
main()
```