Given an array of N numbers. The task is to calculate the Root Mean Square(RMS) of the given numbers.
Examples:
Input: arr[] = {1, 2, 3, 4, 5}
Output: 3.31662
Input: arr[] = {10, 4, 6, 8}
Output: 7.34847
Approach: The Root Mean Square value of N numbers x1,x2,x3,…..xn can be given as,

RMS method first calculates the square of each number and then calculate the mean and finally calculate the square root of the mean.
Below is the program to find RMS of N numbers:
C++
#include <bits/stdc++.h>
using namespace std;
float rmsValue( int arr[], int n)
{
int square = 0;
float mean = 0.0, root = 0.0;
for ( int i = 0; i < n; i++) {
square += pow (arr[i], 2);
}
mean = (square / ( float )(n));
root = sqrt (mean);
return root;
}
int main()
{
int arr[] = { 10, 4, 6, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << rmsValue(arr, n);
return 0;
}
|
Java
class GFG
{
static float rmsValue( int arr[], int n)
{
int square = 0 ;
float mean = 0 ;
float root = 0 ;
for ( int i = 0 ; i < n; i++)
{
square += Math.pow(arr[i], 2 );
}
mean = (square / ( float ) (n));
root = ( float )Math.sqrt(mean);
return root;
}
public static void main(String args[])
{
int arr[] = { 10 , 4 , 6 , 8 };
int n = arr.length;
System.out.println(rmsValue(arr, n));
}
}
|
Python3
import math
def rmsValue(arr, n):
square = 0
mean = 0.0
root = 0.0
for i in range ( 0 ,n):
square + = (arr[i] * * 2 )
mean = (square / ( float )(n))
root = math.sqrt(mean)
return root
if __name__ = = '__main__' :
arr = [ 10 , 4 , 6 , 8 ]
n = len (arr)
print (rmsValue(arr, n))
|
C#
using System;
class GFG
{
static float rmsValue( int [] arr, int n)
{
int square = 0;
float mean = 0;
float root = 0;
for ( int i = 0; i < n; i++)
{
square += ( int )Math.Pow(arr[i], 2);
}
mean = (square / ( float ) (n));
root = ( float )Math.Sqrt(mean);
return root;
}
public static void Main()
{
int [] arr = {10, 4, 6, 8};
int n = arr.Length;
Console.Write(rmsValue(arr, n));
}
}
|
PHP
<?php
function rmsValue( $arr , $n )
{
$square = 0;
$mean = 0.0;
$root = 0.0;
for ( $i = 0; $i < $n ; $i ++)
{
$square += pow( $arr [ $i ], 2);
}
$mean = ( $square / (float)( $n ));
$root = sqrt( $mean );
return $root ;
}
$arr = array ( 10, 4, 6, 8 );
$n = sizeof( $arr );
echo rmsValue( $arr , $n );
?>
|
Javascript
<script>
function rmsValue(arr , n) {
var square = 0;
var mean = 0;
var root = 0;
for (i = 0; i < n; i++) {
square += Math.pow(arr[i], 2);
}
mean = (square / (n));
root = Math.sqrt(mean);
return root;
}
var arr = [ 10, 4, 6, 8 ];
var n = arr.length;
document.write(rmsValue(arr, n).toFixed(5));
</script>
|
Time Complexity: O(n) where n is size of given array, because for loop would run for all elements of array
Auxiliary Space: O(1)