How to generate 64 bit random numbers?

元气小坏坏 提交于 2019-11-29 04:03:12

In C++11 you can use the random header and std::uniform_int_distribution along with a 64-bit instance of std::mersenne_twister_engine this should do what you want (see it live):

#include <iostream>
#include <random>
#include <cmath>

int main()
{
    std::random_device rd;

    std::mt19937_64 e2(rd());

    std::uniform_int_distribution<long long int> dist(std::llround(std::pow(2,61)), std::llround(std::pow(2,62)));

    std::cout << std::llround(std::pow(2,61)) << std::endl; 
    std::cout << std::llround(std::pow(2,62)) << std::endl; 

    for (int n = 0; n < 10; ++n) {
            std::cout << dist(e2)<< ", " ;
    }
    std::cout << std::endl ;
}

If C++11 is not an option then it seems there is source code available for several 64-bit Mersenne Twister implementations.

((long long)rand() << 32) | rand()

EDIT: that's assuming that rand() produces 32 random bits, which it might not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!