Created
October 4, 2016 22:15
-
-
Save joastbg/653fc3c61534da3edeae527ed23709e5 to your computer and use it in GitHub Desktop.
Entropy of Quantum random numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iterator> | |
#include <fstream> | |
#include <algorithm> | |
#include <cstdio> | |
#include <vector> | |
#include <cmath> | |
#include <limits> | |
#include <iomanip> | |
#include <string> | |
#include <map> | |
#define VERBOSE 1 | |
#define ENTROPY 0 | |
double log2( double number ) { | |
return log( number ) / log( 2 ) ; | |
} | |
int entropy(std::string &str, bool disp) { | |
std::map<char, int> frequencies; | |
for (char c : str) { | |
frequencies[c]++; | |
} | |
int numlen = str.length(); | |
double entropy = 0; | |
for (std::pair<char, int> p : frequencies) { | |
double freq = static_cast<double>(p.second) / numlen; | |
entropy += freq * log2(freq); | |
} | |
if (disp) { | |
std::cout << "Entropy is: " << fabs(entropy) << std::endl; | |
} else { | |
std::cout << fabs(entropy) << std::endl; | |
} | |
return 0 ; | |
} | |
int main () { | |
float min = std::numeric_limits<float>::min(); | |
float max = std::numeric_limits<float>::max(); | |
std::cout << std::setprecision(16); | |
std::cout.setf(std::ios::fixed, std:: ios::floatfield); | |
#if VERBOSE | |
std::cout << "Minimum value for float: " << min << "\n"; | |
std::cout << "Maximum value for float: " << max << "\n"; | |
#endif | |
FILE * f; | |
f = fopen("/home/gecemmo/Downloads/ANU_25Jun2014_1000MB/ANU_25Jun2014_100MB_1", "rb"); | |
double sum = 0; | |
int count = 500000; | |
std::string content; | |
for (int i=0;i<count;i++) { | |
unsigned char *ptr = new unsigned char[4]; | |
if (f != NULL) { | |
size_t nr = fread(ptr, sizeof(char), 4, f); | |
if (nr < 4) break; | |
content += std::string((const char*)ptr); | |
unsigned int ui = *reinterpret_cast<unsigned int*>(ptr); | |
float fp = ui / (float)(0xffffffff - 1); | |
#if VERBOSE | |
std::cout << "[" << i << "] "<< fp << std::endl; | |
#endif | |
sum += fp; | |
#if ENTROPY | |
if (i % 5000 == 0) entropy(content, false); | |
#endif | |
} | |
} | |
std::cout << "Average value: " << (sum/count) << " (" << count << " numbers)" << std::endl; | |
#if ENTROPY | |
entropy(content, true); | |
#endif | |
fclose(f); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment