c++ - 耗尽 std::random_device 的熵

标签 c++ random g++ entropy

我正在使用 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/

相关文章:

c# - 具有多个视频帧的DirectShow变换过滤器-与音频同步

c++ - 将一个类与其继承的类对齐?强制所有堆栈对齐?改变尺寸?

java - 设置种子以确定性地在 Java 中随机播放 ArrayList

c# - RNGCryptoServiceProvider 和 Zeros?

c++ - 基于 GLEW 的程序无法编译

C++模拟数字逻辑,实现友元二元运算符

c++ - 我可以空基优化可变数据吗?

algorithm - 您如何确定该算法的平均情况复杂度?

c++ - 错误: to_string was not declared in this scope

c++ - 与tbb::task_arena和tbb::task_scheduler_observer链接时出错