Inspired by my programming question on SO, I'm looking for a function that transforms a list of numbers into a list of interval buckets for a histogram. The programming answers I received were quite error prone, and some broke down for larger numbers. I'd like to know if a more mathematically elegant solution exists.


Input list: 0, 1, 2, 8

The output for an interval of 3 is 3, 0, 1.

Explanation: there are 3 numbers from 0 to 3, 0 numbers from 3 to 6, and 1 number from 6 to 9.

Another example (upper range numbers are exclusive, e.g. from 0 to <3):

Input: 110,111,112,118

Output for interval of 3 is 1, 2, 0, 0, 1

Explanation: 1 number from 108 to 111, 2 numbers from 111 to 114, 0 numbers from 114 to 117, and 1 number from 117 to 120


Once you have $m$, the minimum of the list, and the width $w$, the bin number for $n_i$ is $\lfloor \frac{n_i-m)}{w} \rfloor$ assuming the lowest bin is number $0$. Just go through the list, incrementing the bin numbers for each element. This does not require that the list be sorted.

If the list is sorted, you can compute the lower value of bin $j$ as $m+j\cdot w$ and do a binary search for the first element greater than that. The count inside the bin is the difference of the element numbers for each lower bin.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.