Centering Divisions Around Zero

Posted by Mark on Stack Overflow See other posts from Stack Overflow or by Mark
Published on 2011-01-05T00:50:22Z Indexed on 2011/01/05 0:53 UTC
Read the original article Hit count: 166

Filed under:
|

I'm trying to create something that sort of resembles a histogram. I'm trying to create buckets from an array.

Suppose I have a random array doubles between -10 and 10; this is very simplified. I then want to specify a center point, in this case 0 and the number of buckets.

If I want 4 buckets the division would be -10 to -5, -5 to 0, 0 to 5 and 5 to 10. Not that complicated right. Now if I change the min and max to -12 and -9 and as for 4 divisions its more complicated. I either want a division at -3 and 3; it is centered around 0 ; or one at -6 to 0 and 0 to 6.

Its not that hard to find the division size

= Math.Ceiling((Abs(Max) + Abs(Min)) / Divisions)

Then you would basically have an if statement to determine whether you want it centered on 0 or on an edge. You then iterate out from either 0 or DivisionSize/2 depending on the situation. You may not ALWAYS end up with the specified number of divisions but it will be close. Then you iterate through the array and increment the bin count.

Does this seem like a good way to go about this? This method would surely work but it does not seem to be the most elegant. I'm curious as to whether the creation of the bins and the counting from the list could be done in a clever class with linq in a more elegant way?

Something like creating the bins and then having each bin be a property {get;} that returns list.Count(x=> x >= Lower && x < Upper).

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ