Simple Moving Average is the average obtained from the data for some t period of time . In normal mean, its value get changed with the changing data but in this type of mean it also changes with the time interval. We get the mean for some period t and then we remove some previous data. Again we get new mean and this process continues. This is why it is moving average. This has a great application in the financial market. OR this can be simply visualized as follows.
Given an arr[] of size N, containing only positive integers and an integer K. The task is to compute the simple moving average of previous K elements.Â
Examples:
Input: { 1, 3, 5, 6, 8 }, K = 3
Output: 0.33 1.33 3.00 4.67 6.33
Explanation: New number added is 1.0, SMA = 0.33
New number added is 3.0, SMA = 1.33
New number added is 5.0, SMA = 3.0
New number added is 6.0, SMA = 4.67
New number added is 8.0, SMA = 6.33 Â Â Â ÂInput: Array[]= {2, 5, 7, 3, 11, 9, 13, 12}, K = 2
Output: 1.0 3.5 6 5 7 10 11 12.5
Naive Approach: This uses two nested loops. Outer loop traverses the array from left to right. Inner loop computes the average of K previous elements including itself for each index. Finally, the moving average values are printed. The outer loop starts traversal from index K itself. Instead of storing the result, we can directly display the output to avoid using extra spaces.
Time complexity: O(N*K)
Space complexity: O(1)
Efficient Approach: The efficient approach is discussed in the Set-1 of this problem.
Space Optimized approach: This uses sliding window for better time efficiency and space optimization. A window of size K starts from index K and the moving average is printed for each index thereafter.Â
Below is the implementation of the above approach.Â
C++
// C++ code to find the simple moving average#include <bits/stdc++.h>#include <iomanip>using namespace std;Â
// Function to compute moving average// of previous K elementsvoid ComputeMovingAverage(int arr[], int N,                          int K){    int i;    float sum = 0;Â
    // Initial sum of K elements.    for (i = 0; i < K; i++) {        sum += arr[i];        cout << setprecision(2) << std::fixed;        cout << sum / K << " ";    }Â
    // Compute MA from index K    float avg;    for (i = K; i < N; i++) {        sum -= arr[i - K];        sum += arr[i];        avg = sum / K;        cout << setprecision(2) << std::fixed;        cout << avg << " ";    }}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 1, 3, 5, 6, 8 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â int K = 3;Â Â Â Â ComputeMovingAverage(arr, N, K);Â Â Â Â return 0;} |
Java
// Java code to find the simple moving averageimport java.util.*;class GFG{Â
  // Function to compute moving average  // of previous K elements  static void ComputeMovingAverage(int arr[], int N,                                   int K)  {    int i;    float sum = 0;Â
    // Initial sum of K elements.    for (i = 0; i < K; i++) {      sum += arr[i];      System.out.printf("%.2f ",sum / K);    }Â
    // Compute MA from index K    for (i = K; i < N; i++) {      sum -= arr[i - K];      sum += arr[i];      System.out.printf("%.2f ",sum / K);    }  }Â
  // Driver code  public static void main(String[] args)  {    int arr[] = { 1, 3, 5, 6, 8 };    int N = arr.length;    int K = 3;    ComputeMovingAverage(arr, N, K);  }}Â
// This code is contributed by Rajput-Ji |
Python3
# Python code for the above approachÂ
# Function to compute moving average# of previous K elementsdef ComputeMovingAverage(arr, N, K):    i = None    sum = 0Â
    # Initial sum of K elements.    for i in range(K):        sum += arr[i]        print("%.2f"%(sum / K), end= " ")Â
    # Compute MA from index K    for i in range(K, N):        sum -= arr[i - K]        sum += arr[i]        avg = sum / K        print("%.2f"%(avg), end =" ")Â
# Driver codearr = [1, 3, 5, 6, 8]N = len(arr)K = 3ComputeMovingAverage(arr, N, K)Â
# This code is contributed by Saurabh Jaiswal |
C#
// C# code to find the simple moving averageusing System;Â
class GFG {Â
  // Function to compute moving average  // of previous K elements  static void ComputeMovingAverage(int[] arr, int N,                                   int K)  {    int i;    float sum = 0;Â
    // Initial sum of K elements.    for (i = 0; i < K; i++) {      sum += arr[i];      Console.Write(Math.Round((sum / K),2) + " ");    }Â
    // Compute MA from index K    for (i = K; i < N; i++) {      sum -= arr[i - K];      sum += arr[i];      Console.Write(Math.Round(sum / K, 2) + " ");    }  }Â
  // Driver code  public static void Main(string[] args)  {    int[] arr = { 1, 3, 5, 6, 8 };    int N = arr.Length;    int K = 3;    ComputeMovingAverage(arr, N, K);  }}Â
// This code is contributed by ukasp. |
Javascript
<script>Â Â Â Â Â Â Â // JavaScript code for the above approachÂ
Â
       // Function to compute moving average       // of previous K elements       function ComputeMovingAverage(arr, N,           K) {           let i;           let sum = 0;Â
           // Initial sum of K elements.           for (i = 0; i < K; i++) {               sum += arr[i];               document.write((sum / K).toFixed(2) + " ");           }Â
           // Compute MA from index K           for (i = K; i < N; i++) {               sum -= arr[i - K];               sum += arr[i];               avg = sum / K;               document.write((avg).toFixed(2) + " ");           }       }Â
       // Driver codeÂ
       let arr = [1, 3, 5, 6, 8];       let N = arr.length;       let K = 3;       ComputeMovingAverage(arr, N, K);Â
 // This code is contributed by Potta Lokesh   </script> |
Â
Â
0.33 1.33 3.00 4.67 6.33
Time complexity: O(N)
Space complexity: O(1)Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Find More Info here on that Topic: geeksforgeeks.org/program-to-find-simple-moving-average-set-2/ […]