Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding To Nearest Bin

I have a list of revenue charges that I need to round up or down to the nearest bin.

For example, if the only products sold cost the following:

import numpy as np
bins = np.array([9.95,19.95,79.95])

and I have a few charges like this:

x = np.array([6.68, 9.20, 12.5, 18.75, 21.59])

I followed this example, which is definitely the closest solution:

y = np.take(bins,np.digitize(x,bins))

I thought leaving the right= parameter to the default for np.digitize would accomplish what I needed, but the results are still rounded up:

In [10]: y
Out[10]: array([  9.95,   9.95,  19.95,  19.95,  79.95])

In my particular case, I need to round up or down to the nearest bin. For example, the $12.50 charge is only $2.55 away from $9.95, but the chosen option, $19.95, is $7.45 away.

EDIT

While one answer in the solution I linked to can round both up/down, it appears that method can return inconsistent results, hence this new post.

like image 314
measureallthethings Avatar asked Nov 16 '17 19:11

measureallthethings


1 Answers

If you want to round to certain values you need to split at their midpoints. Like so:

import numpy as np

bins = np.array([9.95,19.95,79.95])
centers = (bins[1:]+bins[:-1])/2

x = np.array([6.68, 9.20, 12.5, 18.75, 21.59])
res = bins[np.digitize(x, centers)]

Gives

array([  9.95,   9.95,   9.95,  19.95,  19.95])
like image 83
Paul Panzer Avatar answered Sep 26 '22 05:09

Paul Panzer