1

我希望能够在可用时使用硬件随机数生成器,并且无论英特尔或 AMD 运行代码如何,都可以使用 C++ 随机库:

void randomDeviceBernouilli(double bernoulliParameter, uint64_t trialCount) {
    std::random_device randomDevice;

    std::cout << "operator():" << randomDevice() << std::endl;
    std::cout << "default random_device characteristics:" << std::endl;
    std::cout << "minimum: " << randomDevice.min() << std::endl;
    std::cout << "maximum: " << randomDevice.max() << std::endl;
    std::cout << "entropy: " << randomDevice.entropy() << std::endl;
    std::bernoulli_distribution bernoulliDist(bernoulliParameter);
    uint64_t trueCount{ 0ull };

    for (uint64_t i = 0; i < trialCount; i++)
        if (bernoulliDist(randomDevice))
            trueCount++;
    std::cout << "Success " << trueCount << " out of " << trialCount << std::endl;
    const double successRate = (double)trueCount / (double)trialCount;
    std::cout << "Empirical: " << std::fixed << std::setprecision(8) << std::setw(10) << successRate << " Theoretical: " << bernoulliParameter << std::endl;
}

根据这篇文章entropy()应该在没有 RDRAND 的 cpu 上返回 0,例如 i7-2670qm ivy 桥(我在其上测试过 - RDRAND 第一次出现在其继任者 Sandy Bridge 中),但在 Visual Studio 中始终为 32如此处所述。有人建议缺少随机设备可能会导致operator()抛出异常,但这也不会发生。

例如,可以使用内在函数int _rdrand32_step (unsigned int* val),但只能从均匀分布中提取,我需要能够利用 C++ 随机库中可用的分布。

此外,代码应该使用 AMD cpu 上的硬件生成器。

random在 Visual Studio(2017、2019)中将硬件随机数生成器(RDRAND)与 C++ 库一起使用的正确方法是什么?

4

1 回答 1

0

在我看来,您应该创建自己的随机数引擎,可供<random>.

就像是

#include <exception>
#include <immintrin.h>
#include <iostream>
#include <limits>
#include <ostream>
#include <random>
#include <stdexcept>
#include <string>

using namespace std::string_literals;

class rdrand
{
public:
    using result_type = unsigned int;
    
    static constexpr result_type min() { return std::numeric_limits<result_type>::min(); }
    static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }

    result_type operator()()
    {
        result_type x;
        auto success = _rdrand32_step(&x);

        if (!success)
        {
            throw std::runtime_error("rdrand32_step failed to generate a valid random number");
        }

        return x;
    }
};

int main()
try
{
    auto engine = rdrand();
    auto distribution = std::bernoulli_distribution(0.75);

    // Flip a bias coin with probability of heads = 0.75
    for (auto i = 0; i != 20; ++i)
    {
        auto outcome = distribution(engine);
        std::cout << (outcome ? "heads"s : "tails"s) << std::endl;
    }

    return 0;
}
catch (std::exception const& exception)
{
    std::cerr << "Standard exception thrown with message: \""s << exception.what() << "\""s << std::endl;
}
catch (...)
{
    std::cerr << "Unknown exception thrown"s << std::endl;
}

指令是否rdrand可用应该是类外部的。您可以添加代码main来测试它。

于 2021-01-02T20:56:54.823 回答