Find the average within variable number of doubles

自古美人都是妖i 提交于 2019-12-24 10:48:07

问题


I have an ArrayList of doubles, and i need to find the average between all numbers. The amount of Double instances in the arraylist is not constant, could be 2, could be 90 I have been trying for hours to get the algorithm myself but could not get it to work in anyway.

do you have any advice? or maybe you can link me to an existing library to get this average?

Thank you


回答1:


Create a sum variable:

double sum = 0;

Go through the elements in the list using a for-loop:

for (double d : yourList)

in each iteration, add to sum the current value:

    sum += d;

after the loop, to find the average, divide sum with the number of elements in the list:

double avg = sum / yourList.size();

Here's for everyone that thinks this was too simple...

The above solution is actually not perfect. If the first couple of elements in the list are extremely large and the last elements are small, the sum += d may not make a difference towards the end due to the precision of doubles.

The solution is to sort the list before doing the average-computation:

Collections.sort(doublesList);

Now the small elements will be added first, which makes sure they are all counted as accurately as possible and contribute to the final sum :-)




回答2:


If you like streams:

List<Number> list = Arrays.asList(number1, number2, number3, number4);

// calculate the average
double average = list.stream()
                     .mapToDouble(Number::doubleValue)
                     .average()
                     .getAsDouble();



回答3:


The definition of the average is the sum of all values, divided by the number of values. Loop over the values, add them, and divide the sum by the size of the list.




回答4:


If by "average between all numbers" you mean the average of all the doubles in your list, you can simply add all the doubles in your list (with a loop) and divide that total by the number of doubles in your list.




回答5:


Have you tried:

List<Double> list = new ArrayList<Double>();
...    
double countTotal = 0;

for (Double number : list)
{
    countTotal += number;
}

double average = countTotal / list.size();



回答6:


Maybe I haven't got the question... but it's not something like this?

double sum = 0.0;
for (double element : list) {
    sum += element;
}
double average = sum / list.size();



回答7:


If you're worried about overflow as you sum the whole list together, you can use a running average. Because it has more operations, it will be slower than adding everything together and dividing once.

for (int x = 0; x < list.size(); x++)
   average = (average / (x+1)) * (x) + list.get(x) / (x+1);


来源:https://stackoverflow.com/questions/10516287/find-the-average-within-variable-number-of-doubles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!