gpt4 book ai didi

在 C 中计算熵

转载 作者:太空宇宙 更新时间:2023-11-04 02:47:16 25 4
gpt4 key购买 nike

我正在尝试查找任何给定文件的熵。然而,当我运行我的程序时,它总是给出 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() 函数的返回类型应该是 float 而不是 int。

关于在 C 中计算熵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25985005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com