-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathEntropy.h
More file actions
29 lines (26 loc) · 651 Bytes
/
Entropy.h
File metadata and controls
29 lines (26 loc) · 651 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#pragma once
#include <cmath>
#include <map>
template <typename T>
static float shannon_entropy(T data[], int elements)
{
float entropy = 0;
std::map<T, long> counts;
typename std::map<T, long>::iterator it;
for (int data_index = 0; data_index < elements; ++data_index)
{
++counts[data[data_index]];
}
it = counts.begin();
while (it != counts.end())
{
const float p_x = static_cast<float>(it->second) / elements;
if (p_x > 0) entropy -= std::log(p_x) * p_x / log(2);
++it;
}
return entropy;
}
inline float calculate_entropy(char* memory, const int count)
{
return shannon_entropy(memory, count);;
}