2014-09-23 107 views
1

我試圖找到任何給定文件的熵。但是,當我運行我的程序時,總是給出3.00000作爲答案。我有一段時間沒有使用C,但我不確定我在哪裏出錯。我現在擺弄了幾個小時。任何提示都會很棒,謝謝!計算熵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; 
} 
+5

在'entropy_calc'內,'entropy'沒有被初始化。 – AlexD 2014-09-23 00:20:49

+6

編譯所有的警告和調試信息('gcc -Wall -g') - 應該給你一個關於你的bug的良好警告。 **使用調試器**('gdb') – 2014-09-23 00:21:31

+1

我沒有看到你在'main'中初始化'length'的位置。您需要檢查所有變量,並確保它們在使用之前被初始化。一個好的編譯器會警告你。 – user3386109 2014-09-23 00:23:51

回答

2

函數entropy_calc()的返回類型應該是float而不是int。

+0

謝謝!你是對的。 – pfinferno 2014-09-23 00:45:49

+0

@AlexD提到的函數中的未初始化熵也很嚴重。 – 2014-09-23 00:52:33