查找双打的变量数内的平均

查找双打的变量数内的平均

本文介绍了查找双打的变量数内的平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有双打的ArrayList,我需要找到所有的数字之间的平均水平。
双实例ArrayList中的量不是恒定的,可以是2,可以是90
我一直在尝试了几个小时,以获得自己的算法,但不能让它反正工作。

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 90I 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?

感谢您

推荐答案

创建一个变量:

double sum = 0;

通过在列表中的元素用转到一个for循环

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;

在循环后,发现平均,分与列表中元素的个数:

double avg = sum / yourList.size();


下面的为大家认为这是太简单 ...

以上的解决方案实际上是不完美的。如果第一对列表中的元素的是非常大的,最后元件是小的,在总和+ = D 可以不使向端的差,由于$ P双打$ pcision。

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 :-)

这篇关于查找双打的变量数内的平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:16