2

I am trying to create histograms of randomly generated data, so currently I am doing the following:

Let's say the following array is created:

returns = [0.0024, 0.0231, 0.014, 0.0005, -0.008]

I go through the array using:

 returnsRounded[x] = Math.round(returns[x] * 1000) / 1000;

And this will return me:

returnsRounded = [0.002, 0.023, 0.014, 0.001, -0.008]

Now I am trying to count the number of each particular value (in an array of tens of thousands of values, so I very inefficiently will do something akin to:

switch (returnsRounded) {
    case -0.040:
        arr[1]++;
        break;
    case -0.038:
        arr[2]++;
        break;
    // ... and so on.
}

And then plug the counted values into my histogram (which works like a bar chart -- in the sense that it only compares counts. I can't just plug in an array and get a histogram.

So is there any more efficient way of counting the number of occurrences of a rounded number in an array that is faster or more pretty than what I'm doing?

Thanks!

Edit: I came up with a much better than my current way, though I don't know if it is still great. Here's a fiddle:

http://jsfiddle.net/brockwhittaker/bLu4s8sc/

1 Answers1

2

They key to counting frequencies is to bin the elements of your array:

function frequencies(values, binsize) {
    var mapped = values.map(function(val) { 
       return Math.ceil(val / binsize) -1; 
    });
    return mapped.reduce(function (freqs, val, i) {
      var bin = (binsize * val);
      freqs[bin] = freqs[bin] ? freqs[bin] + 1 : 1;
      return freqs;
    }, {});
}

The function frequencies creates a dictionary (object) where each key/value pair is the bin/count, e.g.:

Object { 0: 60, 1: 43, 2: 11, -0.2: 68, -2: 11, -2.2: 10, -2.4000000000000004: 4, -2.6: 5, -2.8000000000000003: 1, -3: 1, 18 more… }

A full sample with a simple histogram is available in this jsfiddle

miraculixx
  • 10,034
  • 2
  • 41
  • 60
  • You need to increase your integer by 1. This function shows the numbers incorrectly. – Cybernetic Mar 09 '23 at 17:23
  • 1
    @Cybernetic Thanks, I could not find an issue,as the integer is increased by freqs[bin]++. However, I changed the freqs update to be an explicit assignment for clarity. – miraculixx Apr 13 '23 at 10:03