Search code examples
pythonfeedback-loop

Python feedback loop in order to obtain a specific amount of points in a range about a median


I have a list x of number values.

To begin, I specify a range. I want to grab values from x that lie within this range. The range of values would be ±R from the median of x. I want to adjust R to obtain a specific amount of values N. The only way I can see of achieving this is through some kind of feedback loop. What would be a quick and efficient way of getting closest to N as possible?

eg.

x = ['3','5','1','2','4'] I want the range of values from 3-R<3<3+R as 3 is the median. Let's say N = 3. The obtained values would be ['2','3','4'] with R worked as as 1.

EXAMPLE CODE:

N = 3
x = ['3','5','1','2','4']
R = 1
n = some number to allow room for error
y = values of x in range ±R from median
while len(y) > N+n or len(y) < N-n:
    if len(y) > N+n:
        R -= ADJUST VALUE PROPORTIONAL TO ERROR HERE?
    if len(y) < N-n:
        R += ADJUST VALUE PROPORTIONAL TO ERROR HERE?
    y = values of x in range ±R from median (update y list with new R)

Solution

  • Naively, I'd try kind of a Bolzano theorem approach. You get the median, then the value that is furthest from the median, and call the distance between them L0. That will include all the points, of course. Then you divide L0 by 2 and check how many points lie within the interval. Is it still too many or too little?

    • If too many, L0=L and L = L0/2.
    • If they are too few, L=(L0+L)/2.

    Thus, you will bracket into a solution recursively.