我正在使用 std::random_device
并想检查它的剩余熵。根据 cppreference.com:
std::random_device::entropy
double entropy() const noexcept;
[...]
Return value
The value of the device entropy, or zero if not applicable.
Notes
This function is not fully implemented in some standard libraries. For example, LLVM libc++ always returns zero even though the device is non-deterministic. In comparison, Microsoft Visual C++ implementation always returns 32, and boost.random returns 10.
The entropy of the Linux kernel device /dev/urandom may be obtained using ioctl RNDGETENTCNT - that's what std::random_device::entropy() in GNU libstdc++ uses as of version 8.1
所以在 Linux ang g++ >= 8.1 下,我应该很好......但我不是:
#include <random>
#include <iostream>
void drain_entropy(std::random_device& rd, std::size_t count = 1)
{
while (count --> 0) {
volatile const int discard = rd();
(void) discard;
}
}
int main()
{
std::random_device rd;
std::cout << "Entropy: " << rd.entropy() << '\n'; // Entropy: 32
drain_entropy(rd, 1'000'000);
std::cout << "Entropy: " << rd.entropy() << '\n'; // Entropy: 32
}
Live demo on Coliru (which runs under Linux, right?)
我期望从设备生成数字会耗尽它的熵。但事实并非如此。
发生了什么事?
最佳答案
库不会返回大于其结果类型中的位数的熵值,在本例中为 32。
参见 libstd code :
const int max = sizeof(result_type) * __CHAR_BIT__;
if (ent > max)
ent = max;
您链接到的文档解释了这一点:
Obtains an estimate of the random number device entropy, which is a floating-point value between 0 and log 2(max()+1) (which is equal to std::numeric_limits::digits).
关于c++ - 耗尽 std::random_device 的熵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53944769/