Advertisement

Finding the current average of an indefinitely increasing sequence

Started by October 28, 2015 06:11 PM
3 comments, last by george7378 9 years, 3 months ago
Hi everyone,
The problem I'm currently trying to solve is this: I have a function which generates a value each time it runs, and I want to keep repeating the function indefinitely. Each time the function returns a new value, I want to find the average of ALL of the values it has generated so far. How can I do this without storing every single value?
A bit of context: I'm trying to create a path tracer which will continue to cast rays indefinitely. Each iteration will cast one ray per pixel, and I want to display an average of ALL the rays cast so far, so that I can see the rendering happening in realtime. How can I create a blended image like this without storing every frame?
Thanks a lot, I feel like this is a simple mathematical concept which will be obvious when it is pointed out to me!

You might find this Wiki article on the moving average useful. Specifically, the section on the cumulative moving average looks to me like what you're looking for, but there are discussions and derivations of other methods therein.

Advertisement
You keep track of the number of values that have been produced and the sum of those values. At any time you can compute the average as sum/count.

Another really simple way to do it is to do


newAverage = prevAverage * (i - 1) / i + newValue / i;

, where i starts at 1 and increments after every time you want to add something to the running average. Granted, this is only as good as the floating point precision you're using, but then again, that could be said about almost everything :P

I'm sorry about any spelling or grammar mistakes or any undue brevity, as I'm most likely typing on my phone

"Hell, there's more evidence that we are just living in a frequency wave that flows in harmonic balance creating the universe and all its existence." ~ GDchat

Great - the moving average method is what I was after. As predicted, now that I know about it, it makes perfect sense!

This topic is closed to new replies.

Advertisement