計算變異係數的 C++ 程式


我們給定了一個大小為 n 的浮點陣列,任務是找出變異係數並顯示結果。

什麼是變異係數?

在統計測量中,變異係數用於透過給定的資料找出變異範圍。在金融方面,變異係數用於找出投資額涉及的風險金額。如果標準差與均值之間的比率較低,則投資所涉及的風險也較低。變異係數是標準差與均值之間的比率,由以下公式得出:

變異係數 = 標準差 / 均值 

示例

Input-: array[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0 }
Output-: coefficient of variation is : 0.75772

Input-: array[] = { 15.0, 36.0, 53.67, 25.45, 67.8, 56, 78.09}
Output-: coefficient of variation is : 0.48177

給定程式中使用的解決方法如下:

  • 輸入包含浮點值的陣列
  • 計算給定陣列上的均值和標準差
  • 透過用標準差除以均值來計算變異係數值
  • 將結果作為變異係數顯示 

演算法

Start
Step 1-> declare function to calculate the value of mean
   float cal_mean(float arr[], int size)
   Declare float sum = 0
   Loop For i = 0 and i < size and i++
      Set sum = sum + arr[i]
   End
   return sum / size
Step 2-> declare function to calculate the value of standard deviation
   float StandardDeviation(float arr[], int size)
   Declare float sum = 0
   Loop For i = 0 and i < size and i++
      Set sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] -
   End
   Call cal_mean(arr, size))
   return sqrt(sum / (size - 1))
Step 3-> Declare function to calculate coefficient of variation
   float CoefficientOfVariation(float arr[], int size)
   return StandardDeviation(arr, size) / cal_mean(arr, size)
Step 4-> In main()
   Declare an array of float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0}
   Calculate the size of array as int size = sizeof(arr) / sizeof(arr[0])
   Call function as CoefficientOfVariation(arr, size)
Stop

示例

 實際操作

#include <bits/stdc++.h>
using namespace std;
// function to calculate the mean.
float cal_mean(float arr[], int size) {
   float sum = 0;
   for (int i = 0; i < size; i++)
   sum = sum + arr[i];
   return sum / size;
}
//function to calculate the standard deviation
float StandardDeviation(float arr[], int size) {
   float sum = 0;
   for (int i = 0; i < size; i++)
   sum = sum + (arr[i] - cal_mean(arr, size)) * (arr[i] - cal_mean(arr, size));
   return sqrt(sum / (size - 1));
}
// function to calculate the coefficient of variation.
float CoefficientOfVariation(float arr[], int size) {
   return StandardDeviation(arr, size) / cal_mean(arr, size);
}
int main() {
   float arr[] = { 10.0, 21, 23, 90.0, 10.5, 32.56, 24, 45, 70.0};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"coefficient of variation is : "<<CoefficientOfVariation(arr, size);
   return 0;
}

輸出

coefficient of variation is : 0.75772

更新時間:2019-12-23

607 次瀏覽

啟動您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.