玩排序算法;这里是第一位:
/** Finding if C is the minimum or maximum in a value set*/
method giveValue(c):
private value minimum
private value maximum
private value average
if c < minimum
minimum = c
if c > maximum
maximum = c
有趣的是确定平均值…
我提出了两个解决方案:
/** Detemine the average by maintaining a new variable*/
private variable total
total += c
count++
average = total/count
但我也可以这样做:
/** multiply the average to its previous form.
(Avoids creating another private variable) */
average * count
count ++
average = (c + average) / count
不可避免地,这个方法只想知道集合中的最小值、平均值和最大值,这让我感到疑惑:
会不会更快:
不断地乘以一个变量?
不断增加第二个变量?
如果这意味着什么的话,我在java中练习所有这些,所以我从维护类的角度来看。
最佳答案
总的解是目前为止最好的,也有最好的精度。
另一个解决方案累积浮点不精确性,并执行至少一个无关的除法或乘法:
++count;
那么下面是等价的
average = (c + average * (count - 1)) / count;
average = (c - average + average * count) / count;
average = (c - average) / count + average;
average += (c - average) / count;
最后一个看起来很好。
关于java - 哪个需要更多内存:将一个变量乘以还是将第二个变量递增?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36267716/