Re: Avoiding Overflow



Jason Doucette <www.jasondoucette.com> wrote:
> I can see what you are trying to accomplish. How about this formula:
>
> average of first 2:
> avg2 = (x1+x2)/2
>
> average of first 3, using the above:
> avg3 = (avg2 + x3/2) * 2 / 3
> the divide by 2 is required to give x3 the same weight as x1 and x2,
> but this leaves the result: (x1+x2+x3)/2, and we wish to divide this
> by 3, not 2, thus multiple by 2, then divide by 3.
>
> average of first 4 (same logic):
> avg4 = (avg3 + x4/3) * 3 / 4
>
> average of first 5:
> avg5 = (avg4 + x5/4) * 4 / 5
>
> etc.
>
> Thus:
>
> ((((((x1+x2)/2) + x3/2) * 2/3) + x4/3) * 3/4) + ... + xn/(n-1)) *
> (n-1)/n

Yes, that's what I meant. Or perhaps

(((x1 * 1/2 + x2 * 1/2) * 2/3 + x3 * 1/3) * 3/4 + x4 * 1/4) + ...

avg[i] = avg[i - 1] * (i - 1)/i + x[i] / i;

If calculated in the correct order, no subexpression can produce a value
larger than max(1, max(x[i]))
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925


.



Relevant Pages