用C计算分散度

时间:2015-04-20 21:20:48

标签: c math

我试图计算两个值之间的离散度,一个来自结构数组中每个条目的一个参数(' age')。

我有一个辅助的.txt文件,这一点的重点是分别遍历.txt文件的每一行(每行都是一个字符串)。如果我陈述一个例子,那就更好了,所以,我们走了:

matrix[n][n]:
1 2 3 4 
1 2 3 
1 2 

所以,结构看起来有点像这样:

struct person {
  int id; //where im comparing between the matrix and the structure;
  int age; //what I need to calculate the dispersion
}

我要比较.txt每行的每个值,如果它与结构中的任何id匹配,我必须得到它的年龄。现在是棘手的部分。

要计算分散度,我需要为我做以下工作:

让我们以.txt文件的第一行为例:分散将是:

让我们说' age' = id(n)的年龄;

//in this case nGroups = 6 (number of age(n)-age(m) operations)
dispersion(first_row)= [ [|age(1)-age(2)|] + [|age(1)-age(3)|] + [|age(1)-age(4)|] + [|age(2)-age(3)|] + [|age(2)-age(4)|] + [|age(3)-age(4)|] ]/nGroups

所以我必须为矩阵的每一行做这个。我已经尝试过并管理了以下代码,但是在“数学”中这样做了。部分我的大脑冻结了一点。

// going through each line of the matrix
for(i=0; i<nconjuntos; i++) {
  // going through each column of the matrix
  for(j=0; j<strlen(aux[i]); j++) {
    // going through all the structures in the structure array
    for(k=0; k<TOTAL; k++) {
      // comparing each number with it's id equivalent in
      // each structure.id parameter in the array
      if(aux[i][j] - 48 == pessoas[k].id) { 

      }
    }
  }
}

任何有助于我推进代码的帮助都会非常感激!

1 个答案:

答案 0 :(得分:0)

这里有两个问题需要解决方案:

  • 将矩阵中的id与结构中的id匹配,并获取给定行的年龄列表
  • 计算色散

如果将这两个任务分开,而不是在同一个嵌套for循环中执行它们,这可能是最简单的。您可以根据您给出的公式编写一个函数来计算色散:

double calculateDispersion(double* values, int count)
{
    if(count < 2)
        return 0.0;   // need at least 2 values
    double total = 0.0;
    // iterate through each combination of values and sum the absolute
    // differences of each combination:
    int i, j;
    for(i = 0; i < (count - 1); i++)
    {
        for(j = i + 1; j < count; j++)
        {
            double difference = values[i] - values[j];
            if(difference < 0.0)   // find absolute value
                difference = 0.0 - difference;
            total += difference; // add to the total
        }
    }
    int groups = (count * (count - 1)) / 2;
    return total / (double)groups; 
}

在主循环中创建一个双精度数组,其大小与矩阵中最大的行相等,以存储当前行的年龄(或浮点数,但使用整数会给出舍入错误)。通过交叉引用包含id和age的结构来填充它。然后调用calculateDispersion()来计算行的色散。

大概就是这样:

double rowArray[MAX_SIZE]; // or initialize to maximum matrix row length dynamically

// going through each line of the matrix
for(i=0; i<nconjuntos; i++) {
  int count = 0;
  // going through each column of the matrix
  for(j=0; j<strlen(aux[i]); j++) {
    // going through all the structures in the structure array
    for(k=0; k<TOTAL; k++) {
      // comparing each number with it's id equivalent in
      // each structure.id parameter in the array
      if(aux[i][j] - 48 == pessoas[k].id) { 
          // set array value:
          rowArray[count++] = (double)pessoas[k].age;
          break; // break out of the loop
      }
    }
  }
  // compute the dispersion for the row:
  doubleDispersion = calculateDispersion(rowArray, count);
}