# Finding the current average of an indefinitely increasing sequence

This topic is 988 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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!

##### Share on other sites

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.

##### Share on other sites

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

##### Share on other sites

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

1. 1
Rutin
25
2. 2
JoeJ
20
3. 3
4. 4
5. 5

• 9
• 9
• 46
• 41
• 23
• ### Forum Statistics

• Total Topics
631750
• Total Posts
3002051
×