Notification texts go here Contact Us Buy Now!

How to calculate moving average without keeping the count and data-total?

```html

How to calculate moving average without keeping the count and data-total?

Here's a simple and efficient way to calculate the moving average of a stream of data without keeping track of the count or the data-total:


double approxRollingAverage (double avg, double new_sample) {

    avg -= avg / N;
    avg += new_sample / N;

    return avg;
}

In this code:

  • avg is the current moving average.
  • new_sample is the new data point to be added to the moving average.
  • N is the number of samples over which the moving average is calculated.

To use this function, simply call it with the current moving average and the new data point. The function will return the updated moving average.

For example, the following code calculates the moving average of the numbers 1, 2, 3, 4, and 5:


double avg = 0;
for (int i = 1; i <= 5; i++) {
    avg = approxRollingAverage(avg, i);
    System.out.println(avg);
}

This code will print the following output:


1.0
1.5
2.0
2.5
3.0

As you can see, the moving average starts at 1 and gradually increases as new data points are added.

This method is known as the "Welford's algorithm" and it is a very efficient way to calculate the moving average of a stream of data.

```

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.