pceccon
pceccon

Reputation: 9844

Find closer number of a value considering given intervals - Python

I have to build a kind of an histogram, with given bins (I don't know if this is the best name to call them). To exemplify:

The bins are:

-0.15|-0.10|-0.05|0.0|0.05|0.10|0.15

As input, I have a matrix which its values are between -0.16, 0.16, e.g. So, if I read a 0.0884, I have to count it as 0.10. I know that, to do this, I could verify in what range this value fits, i.e, [0.05, 0.10]. The I could calculate the difference between the value and its upper bound and lower bound (each value in absolute). So, the value would be counting as in the bin with the smallest difference. But I found so simple codes to do really complex things in Python that I'm know wondering if there is a simple way to do this.

Thanks.

Upvotes: 0

Views: 404

Answers (2)

mcalmeida
mcalmeida

Reputation: 562

You want a Histogram, so I assume you want to allocate points in an ordered list of bins. So here goes:

bins = ((-0.15,[]), (-0.10,[]), (-0.05,[]), (0.00,[]), (0.05,[]), (0.10,[]), (0.15,[]))

def store(point):
    for bin in bins:
        if point < bin[0]:
            bin[1].append(point)
            return
    bins[len(bins)-1][1].append(point)

store(0.0884)

bins

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208475

def get_bin(n, step=0.05):
    return step * round(n / step)

Examples:

>>> get_bin(0.0884)
0.1
>>> get_bin(-0.027)                                                                                                   
-0.05
>>> get_bin(-0.023)                                                                                                   
-0.0

This method is described well here: https://stackoverflow.com/a/2272174/505154

Upvotes: 4

Related Questions