如何找到向量的统计信息?最大值/最小值、众数、中值、平均值

Posted

技术标签:

【中文标题】如何找到向量的统计信息?最大值/最小值、众数、中值、平均值【英文标题】:How to find the statistics of a vector? Max/Min, mode, median, mean 【发布时间】:2016-02-07 04:18:57 【问题描述】:

我的任务是向用户询问最小和最大 x 值。然后,我使用极端值来计算这些极端值之间的 20 个值。我必须在表格上显示 x 值和它的 f(x) 值。然后我必须找到 f(x) 值的统计数据,例如最小值和最大值、平均值、众数和中位数。我对向量不够熟悉,无法找到这些统计数据。任何帮助表示赞赏。到目前为止,这是我的代码...

#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>

using namespace std;

int main()

   double xmin, xmax;
   const int POINTS = 20;
   const double PI = 3.1416;
   double increments;
   int counter = 0;

   vector<vector<float> > values;

   cout << "Enter in a value for the minimum x value: ";
   cin >> xmin;
   cout << "Enter in a value for the maximum x value: ";
   cin >> xmax;

   increments = (abs(xmin) + xmax) / POINTS;

   double x = xmin + increments * counter;
   double min = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
   double max = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);

   cout << setw(15) << "x |" << setw(15) << "f(x)" << endl;
   cout << setw(32) << setfill('-') << " " << endl;
   cout << setfill(' ');
   vector<float> auxiliar;

   while (x <= xmax)
   
      auxiliar.resize(2);
      auxiliar[0] = x;
      auxiliar[1] = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);

      values.push_back(auxiliar);
      auxiliar.clear();

      if (0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x) > max)
         max = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
      if (0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x) < min)
         min = 0.0572 * cos(4.667 * x) + 0.0218 * PI * cos(12.22 * x);
      counter++;
      x = xmin + increments * counter;

   

   for(vector<float> i:values)
     cout << fixed << showpos << setw(15) << setprecision(2) << i[0] <<         setw(15) << setprecision(4) << i[1] << endl;

system("pause");
return 0;
 

【问题讨论】:

你把答案拿掉了 如果我们向您展示如何访问向量的元素,您知道如何使用它们来计算最小值、最大值等吗? 我知道如何使用std::sort从低到高对它们进行排序,最小值是第一个元素,最大值是n-1个元素。 你不用解释怎么做,我只想知道你是否知道怎么做,这样我就知道你需要什么帮助和。现在我提到的 etc. 其他统计数据怎么样? 我不确定众数、均值和中位数 【参考方案1】:

vector&lt;int&gt; 为例。获取元素的一种粗略但有效的方法是这样的:

for(int i=0; i<vec.size(); ++i)

  int n = vec[i];
  ...

现在vector&lt;vector&lt;int&gt;&gt;:

for(int i=0; i<vec.size(); ++i)
  for(int j=0; j<vec[i].size(); ++j)
  
    int n = vec[i][j];
    ...
  

【讨论】:

以上是关于如何找到向量的统计信息?最大值/最小值、众数、中值、平均值的主要内容,如果未能解决你的问题,请参考以下文章

查找地图中的最大值

备战数学建模5-数据统计分析多项式计算

Excel的一些统计函数

Excel的一些统计函数

用R进行统计学分析

所有可能和的最小值、最大值、平均值和中值 (Ruby)