Please help - get average
Robin Becker
robin at SPAMREMOVEjessikat.fsnet.co.uk
Wed Oct 27 04:07:59 EDT 2004
Cliff Wells wrote:
......
>
> total = 0.0
> count = 0
> number = None
>
> while number not in ('q', 'Q'):
> number = raw_input("Enter a number (or Q to quit): ")
> try:
> number = float(number)
> except ValueError:
> continue
> total += number
> count += 1
>
> print "The average is:", total / count
>
...... interestingly the standard algorithms for means/deviations are
numerically poor. As an example
>>> (1.e30+1-1.0e30)/3
0.0
Where we have total loss of information in one of the terms.
There are better algorithms involving recursion,
eg
mu[n] = (data[n]+(n-1)*mu[n-1])/n
The error in the existing estimate, mu[n-1], gets multiplied by the
number (n-1)/n which is less than one (ie the errors are damped).
However, in the case of widely differing magnitudes I think you need to
accumulate the sums specially.
--
Robin Becker
More information about the Python-list
mailing list