Home > Enterprise >  matching the down the lower float
matching the down the lower float

Time:01-04

there is a list of voltage that I need to find the closest number

voltage_map= [11.65,11.75,11.85,11.95]

I want to match to the closest and lowest number so I have the function below

def close_vol(list,K):
    return list[min(range(len(list)), key = lambda i: abs(list[i]-K))]

However, the function would return the closest but not the lowest.

when I set K = 11.70 close_vol(voltage_map,11.70),it matched 11.75, whereas I expect it to round down to 11.65

when I set K = 11.84 close_vol(voltage_map,11.84),it matched 11.85, I do want it to round down to 11.75

Anyone would know what should I add into the function above?

CodePudding user response:

You could use the bisect module to discover where a given k falls withing voltage_map:

from bisect import bisect_left

voltage_map = [11.65,11.75,11.85,11.95,12.05,12.15,12.25,12.35,12.45,12.55,12.65,12.75]

def close_vol(k):
    i = max(0, bisect_left(voltage_map,k) - 1)
    return voltage_map[i]

#test

for k in [11.5   (0.25)*k for k in range(7)]:
    print(k,close_vol(k))

'''
11.5 11.65
11.75 11.65
12.0 11.95
12.25 12.15
12.5 12.45
12.75 12.65
13.0 12.75
'''

Note that in this code any k which falls outside of the given voltage range is sent to the nearest voltage range endpoint.

CodePudding user response:

I think you're trying to find the closest voltage that is below your inputted value?

Assuming that voltages is a list of the voltages that you've screenshotted, you could do something like this

voltages = [11.65, 11.75, ...]
def close_vol(K):
    if K < min(voltages):
        raise ValueError("`K` is less than every voltage value")
    return max([i for i in voltages if K >= i])
  • Related