/*
* entropy.c * * Calcula la entropía de una secuencia de símbolos de 8 bits. * */ #include <stdio.h> #include <stdlib.h> #include <math.h> /* * Tamaño del alfabeto fuente. */ #define ALPHABET_SIZE 256 double entropy(unsigned long *count, int alphabet_size) { double entropy = 0.0; unsigned long total_count = 0; int i; for(i=0; i<alphabet_size; i++) { total_count += count[i]; } for(i=0; i<alphabet_size; i++) { if(count[i]) { double prob = (double)count[i]/total_count; entropy += prob*log(prob)/log(2.0); } } return -entropy; } int main(int argc, char *argv[]) { unsigned long count[ALPHABET_SIZE]; int i; for(i=0; i<ALPHABET_SIZE; i++) { count[i] = 0; } for(;;) { int x = getc(stdin); if(x==EOF) break; count[x]++; } for(i=0; i<ALPHABET_SIZE; i++) { fprintf(stderr, "%3d %u\n", i, count[i]); } fprintf(stderr, "Entropy = "); fflush(stderr); fprintf(stdout, "%f\n", entropy(count,256)); } |