Skip to content

Instantly share code, notes, and snippets.

@airglow923
Last active September 4, 2020 18:11
Show Gist options
  • Save airglow923/4864b1c730c4bf43092623ee82e018d2 to your computer and use it in GitHub Desktop.
Save airglow923/4864b1c730c4bf43092623ee82e018d2 to your computer and use it in GitHub Desktop.
Calculate entropy using modern C++
#include <cassert>
#include <cmath>
#include <concepts>
namespace phd {
template<typename T>
concept numeric = std::integral<T> || std::floating_point<T>;
template<numeric Arg, std::integral Base>
auto log(Arg argument, Base base = 10)
{
assert(base > 0);
return std::log(argument) / std::log(base);
}
}
template<std::integral Choice, std::integral... Uncertainty>
auto get_entropy(Choice choices, Uncertainty... uncertainties)
{
assert(choices > 0);
assert((... && (uncertainties >= 1)));
return (... + (((long double) uncertainties / choices) *
phd::log((long double) choices / uncertainties, 2)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment