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

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

def interval_length(i):
    if i <= 0:
        return 0
        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)
    a = belong(150, a)
    a = belong(179, a)
    a = belong(560, a)
    a = belong(123, a)
    a = belong(999, a)

if __name__ == '__main__':

1 Comment

  1. Reblogged this on One day at a time and commented:
    Although my experience with Python is limited to what university assignments recommended it as a programming language and some other smaller projects of my own, I’ve found reasons to love (and to hate) it. A former fellow student of mine, Dimitris, is obviously in love with it, and I don’t mean that in a bad way. His book on the language is one of the best programming language guides I’ve ever read, and his blog approaches a lot of problems, some less common than others, using Python. Here’s his approach on avoiding fluctuations around a threshold, based on a post from another fellow student, and friend, Vasilis.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: