首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用C++计算熵

用C++计算熵
EN

Stack Overflow用户
提问于 2014-09-23 08:19:16
回答 1查看 4.9K关注 0票数 2

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

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2014-09-23 08:23:47

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25985005

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档