home / system / tools_source

Menu
  • GraphQL API
  • Search all tables

tools_source: 13

This data as json

id tool_id filename language content
13 2 entropy.c c /* entropy — calculate shannon entropy of input */ #include <math.h> #include <stdio.h> int main(int argc, char *argv[]) { FILE *fp; unsigned long freq[256] = {0}; unsigned long total = 0; int c; double entropy = 0.0; fp = (argc > 1) ? fopen(argv[1], "rb") : stdin; if (!fp) { perror(argv[1]); return 1; } while ((c = fgetc(fp)) != EOF) { freq[c]++; total++; } if (fp != stdin) fclose(fp); if (total == 0) { printf("0.000000\n"); return 0; } for (int i = 0; i < 256; i++) { if (freq[i] == 0) continue; double p = (double)freq[i] / total; entropy -= p * log2(p); } printf("%.6f\n", entropy); return 0; }
Powered by Datasette · 0.846ms · krisyotam.com