【问题标题】:Calculating entropy in C在 C 中计算熵
【发布时间】:2014-09-23 00:19:15
【问题描述】:

我正在尝试查找任何给定文件的熵。但是,当我运行我的程序时,它总是给出 3.00000 作为答案。我有一段时间没有使用 C,但我不确定我在哪里出错了。我已经摆弄了几个小时了。任何提示都会很棒,谢谢!

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#define SIZE 256

int entropy_calc(long byte_count[], int length)
{
      float entropy;
      float count;
      int i;

      /* entropy calculation */
      for (i = 0; i < SIZE; i++)
        {
          if (byte_count[i] != 0)
            {
              count = (float) byte_count[i] / (float) length;
              entropy += -count * log2f(count);
            }
        }
      return entropy;
}

int main(int argc, char **argv)
{
  FILE            *inFile;
  int             i;              
  int             j;              
  int             n;              // Bytes read by fread;
  int             length;         // length of file
  float           count;
  float           entropy;
  long            byte_count[SIZE];
  unsigned char   buffer[1024];

  /* do this for all files */
  for(j = 1; j < argc; j++)
    {
      memset(byte_count, 0, sizeof(long) * SIZE);

      inFile = fopen(argv[j], "rb");    // opens the file given on command line

      if(inFile == NULL)                // error-checking to see if file exists
        {
          printf("Files does not exist. `%s`\n", argv[j]);
          continue;
        }

      /* Read the whole file in parts of 1024 */
      while((n = fread(buffer, 1, 1024, inFile)) != 0)
        {
          /* Add the buffer to the byte_count */
          for (i = 0; i < n; i++)
            {
              byte_count[(int) buffer[i]]++;
              length++;
            }
        }
      fclose(inFile);

      float entropy = entropy_calc(byte_count, length);
      printf("%02.5f \t%s\n", entropy, argv[j]);
    }
  return 0;
}

【问题讨论】:

  • entropy_calc内,entropy未初始化。
  • 编译所有警告和调试信息 (gcc -Wall -g) - 这应该会给你一个关于你的错误的很好的警告。 使用调试器 (gdb)
  • 我看不到您在 main 中初始化 length 的位置。您需要检查所有变量,并确保在使用它们之前对其进行初始化。一个好的编译器应该警告你。
  • 关于“文件的熵”,您可能会发现this answer 是一个有趣的读取(TL;DR: 一个文件(或一组固定的字节)不有熵。)
  • 非常感谢大家,只是为了说明已经过了多久。我混淆了声明和初始化值,返回类型错误。现在一切都很好,再次感谢。

标签: c entropy


【解决方案1】:

你的函数entropy_calc()的返回类型应该是float而不是int。

【讨论】:

  • @AlexD 提到的函数中未初始化的熵也很严重。
猜你喜欢
  • 2015-01-31
  • 2021-11-14
  • 2017-07-20
  • 2013-06-10
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多