更好的算法来找到平均 [英] Better algorithm to find average

查看:129
本文介绍了更好的算法来找到平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做练习的编程书籍的​​一书基于C 的。演习表明,发现平均的一组号码中,算法:

I am doing an exercise of a programming book A Book on C . The exercise suggests that to find average of a group of numbers, algorithm:

avg += (x - avg) / i;

优于:

sum += x;
avg = sum / i;

的x是用来存储输入数的变量。这也表明preventing溢出旁边,第一个算法确实有比第二algorthim一些其他的好处,谁能帮助我?谢谢!

'x' is a variable used to store the input numbers. It also suggests beside preventing overflow, the first algorithm do have some other benefits than the second algorthim, can anyone help me? Thanks!

推荐答案

我假设我们在谈论浮点运算这里(否则精益求精的平均水平将是可怕的)。

I'm assuming we're talking about floating-point arithmetic here (otherwise the "better" average will be terrible).

在第二种方法,中间结果()将倾向于无限制地增长,这意味着你最终失去低端precision。在第一种方法,中间结果应保持在大致相同幅度的输入数据(假设你的输入不产生巨大的动态范围)。这意味着它将保留precision更好

In the second method, the intermediate result (sum) will tend to grow without bound, which means you'll eventually lose low-end precision. In the first method, the intermediate result should stay of a roughly similar magnitude to your input data (assuming your input doesn't have an enormous dynamic range). which means that it will retain precision better.

然而的,我可以想像,作为变得越来越大,价值(X - AVG) /我会越来越少准确的(相对)。因此,它也有它的缺点。

However, I can imagine that as i gets bigger and bigger, the value of (x - avg) / i will get less and less accurate (relatively). So it also has its disadvantages.

这篇关于更好的算法来找到平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆