I’m trying to find a way to snap or quantize numbers to specific values after a math operation and don’t really know the best way to approach the problem.
A specific example:
I have a list of numbers that I want to be my master numbers – 5, 10, 30, 60, 120, 180
I have a list of numbers that are currently inputted – 10, 20, 60, 120
Now I want to multiply all the inputted numbers by 2, and have them snap (or quantize/get rounded to) the nearest of my master numbers.
So a number like 10, once multiplied by two, I’d like to have it snap to 30. I dont think it’s a big problem for the top or bottom because I think I can use math.ceil and math.floor to contain the ends. Similarly I’d like 20 to be rounded to 30 as well (20*2=40, rounded down as 30 is closer than 60).
I saw a similar question in regards to rounding to 10s, 100s, etc, but can’t really figure out how to apply the answer there, as I’m still relatively new! : )
Use the
bisectmodule to quickly pinpoint the desired quantity:Midpoints are rounded to the larger quantity; change
bisect_righttobisect_leftto round to the smaller one instead.For simplicity, this implementation recreates the
midslist each time it is called. An efficient implementation would reuse the midpoints, and would run withO(log n)worst-case complexity.