Advertisement
bartekltg

entropy_code

Sep 4th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <iostream>
  4. //#include <omp.h>
  5. //#include <bitset>
  6. #include <cstdint>
  7. //#include <chrono>
  8. //#include <random>
  9. #include <functional>
  10. #include <vector>
  11. #include <cmath>
  12.  
  13. using namespace std;
  14.  
  15. //#include <boost/functional/hash.hpp>
  16.  
  17. uint32_t hash32( uint32_t a)
  18. {
  19.    a = (a+0x7ed55d16) + (a<<12);
  20.    a = (a^0xc761c23c) ^ (a>>19);
  21.    a = (a+0x165667b1) + (a<<5);
  22.    a = (a+0xd3a2646c) ^ (a<<9);
  23.    a = (a+0xfd7046c5) + (a<<3);
  24.    a = (a^0xb55a4f09) ^ (a>>16);
  25.    return a;
  26. }
  27.  
  28. double HH(int m, int k)
  29. {// entropy of k-bits sequences generated from m bits random variable
  30.      int N = 1<<m;
  31.  
  32.      int  K =  1<<k;
  33.     vector<int> counts(K );
  34.  
  35.  
  36.  
  37.     for (int i=0;i<N;i++)
  38.     {
  39.         uint32_t x = hash32(i);
  40.        // cout<<x<<" "<<i<<endl;
  41.         counts[(x)%K]++;
  42.     }
  43.     double H=0;
  44.     for (int i=0;i<counts.size();i++)
  45.     {
  46.         double P = counts[i]/(double)N;
  47.         if (P > 0)
  48.             H+= -P*log2(P);
  49.     }
  50.     return H;
  51. }
  52.  
  53.  
  54. int main(void)
  55. {
  56.  
  57.     cout.precision(2);
  58.     std::cout.setf( std::ios::fixed, std:: ios::floatfield );
  59.  
  60.     cout<<"  ";
  61.     for (int m=1;m<=20;m++)
  62.     {
  63.         std::cout.fill(' ');
  64.         std::cout.width(5);
  65.         cout<<m<<" ";
  66.  
  67.     }
  68.     cout<<endl;
  69.  
  70.     for (int k=1;k<25;k++)
  71.     {
  72.         std::cout.fill(' ');
  73.         std::cout.width(2);
  74.         cout<<k<<":";
  75.         for (int m=1;m<=20;m++)
  76.         {
  77.             std::cout.fill(' ');
  78.             std::cout.width(5);
  79.             cout<<(HH(m,k))<<" ";
  80.         }
  81.               cout<<endl;
  82.     }
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement