📜  程序计算均方根

📅  最后修改于: 2021-05-04 17:27:30             🧑  作者: Mango

给定一个N个数字的数组。任务是计算给定数字的均方根(RMS)。
例子

Input: arr[] = {1, 2, 3, 4, 5}
Output: 3.31662

Input: arr[] = {10, 4, 6, 8}
Output: 7.34847

方法: N个数字x1,x2,x3,…..xn的均方根值可以表示为:

RMS方法首先计算每个数字的平方,然后计算平均值,最后计算平均值的平方根。
下面是查找N个数字的RMS的程序:

C++
// CPP program to calculate Root Mean Square
#include 
using namespace std;
 
// Function that Calculate Root Mean Square
float rmsValue(int arr[], int n)
{
    int square = 0;
    float mean = 0.0, root = 0.0;
 
    // Calculate square.
    for (int i = 0; i < n; i++) {
        square += pow(arr[i], 2);
    }
 
    // Calculate Mean.
    mean = (square / (float)(n));
 
    // Calculate Root.
    root = sqrt(mean);
 
    return root;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 4, 6, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << rmsValue(arr, n);
 
    return 0;
}


Java
// Java program to calculate
// Root Mean Square
 
class GFG
{
 
// Function that Calculate Root
// Mean Square
static float rmsValue(int arr[], int n)
{
    int square = 0;
    float mean = 0;
    float root = 0;
 
    // Calculate square.
    for(int i = 0; i < n; i++)
    {
        square += Math.pow(arr[i], 2);
    }
     
    // Calculate Mean.
    mean = (square / (float) (n));
 
    // Calculate Root.
    root = (float)Math.sqrt(mean);
 
    return root;
}
 
 
// Driver Code
public static void main(String args[])
{
    int arr[] = { 10, 4, 6, 8};
     
    int n = arr.length;
     
    System.out.println(rmsValue(arr, n));
}
}
 
// This code is contributed by ANKITRAI1


Python3
#Python3 program to calculate Root Mean Square
 
import math
#Function that Calculate Root Mean Square
def rmsValue(arr, n):
    square = 0
    mean = 0.0
    root = 0.0
     
    #Calculate square
    for i in range(0,n):
        square += (arr[i]**2)
     
    #Calculate Mean
    mean = (square / (float)(n))
     
    #Calculate Root
    root = math.sqrt(mean)
     
    return root
 
#Driver code
if __name__=='__main__':
    arr = [10, 4, 6, 8]
    n = len(arr)
    print(rmsValue(arr, n))
 
#This code is contributed by Shashank_Sharma


C#
// C# program to calculate
// Root Mean Square
using System;
class GFG
{
 
// Function that Calculate
// Root Mean Square
static float rmsValue(int[] arr, int n)
{
    int square = 0;
    float mean = 0;
    float root = 0;
 
    // Calculate square.
    for(int i = 0; i < n; i++)
    {
        square += (int)Math.Pow(arr[i], 2);
    }
     
    // Calculate Mean.
    mean = (square / (float) (n));
 
    // Calculate Root.
    root = (float)Math.Sqrt(mean);
 
    return root;
}
 
// Driver Code
public static void Main()
{
    int[] arr = {10, 4, 6, 8};
     
    int n = arr.Length;
     
    Console.Write(rmsValue(arr, n));
}
}
 
// This code is contributed
// by ChitraNayal


PHP


Javascript


输出:
7.34847