yoman
yoman

Reputation: 33

Create histogram of array with doubles

I have an array including doubles:

double[] myArray = {1.23455, 1.23456, 2.45673, 6.45678, 8.12938}

The numbers in the array and the number of elements in array will vary. How can I create a histogram out of this array? I'm trying to create ranges by doing something like this:

double sizeOfRange = (max-min)/(numberOfRanges-1);

Where max and min are max and min values in myArray, but other than that I am completely lost regarding how to do this. I'm very new to java, hope the question is asked correctly.

Upvotes: 0

Views: 722

Answers (1)

Marco Luzzara
Marco Luzzara

Reputation: 6026

I'm not sure this is what you want, but it certainly can help you if you are starter:

    Double[] myArray = {1.23455, 1.23456, 2.45673, 6.45678, 8.56938, 3.65645, 5.65478, 2.54773, 9.63345};
    int nRanges = 3;
    int[] buckets = new int[nRanges];
    double max = Collections.max(Arrays.asList(myArray));
    double min = Collections.min(Arrays.asList(myArray));
    double sizeOfRange = (max-min)/(nRanges - 1);

    for (double elem : myArray){
        for (int i = 0; i < nRanges; i++){
            if ((elem >= sizeOfRange * i) && (elem < sizeOfRange * (i + 1)))
                buckets[i]++;
        }
    }

    for (int i = 0; i < nRanges; i++){
        System.out.println(sizeOfRange * i + " - " + sizeOfRange * (i + 1) + ": " + buckets[i]);
    }

Collections class provides a lot of useful method, just like max and min. Then the core of this code is from line 8 to 13: inside that for I am incrementing the frequency of the range in which the correspondent double value can be placed.

Upvotes: 1

Related Questions