如何生成64位随机数? [英] How to generate 64 bit random numbers?
问题描述
我正在实现通用散列并使用以下通用散列函数:
h(k)=((A * k) mod 2 ^ 64)rsh 64-r
其中A是
之间的随机数
2 ^ 61和2 ^ 62。
()函数在 C ++ 中返回类型 integer ,它不能生成大数字。那么如何在这个范围内产生随机数? (数字应该是非常随机的,即每个数字应该具有相等的选择概率)
注意:
long long int random = rand();
不能作为 rand $ c $ 在 C ++ 11 中,您可以在 可以使用随机标头和 std :: uniform_int_distribution 以及 64位std :: mersenne_twister_engine的实例,这应该做你想要的( 实时查看 ):
#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;
}
如果 C ++ 11 那么它似乎有源代码可用于几个64位Mersenne Twister实现。
I'm implementing universal hashing and using the following universal hash function :
h(k)=((A*k)mod 2^64) rsh 64-r
where A is a random number between
2^61 and 2^62.
The rand()
function in C++ has return type integer and it can't generate that big numbers. So how can i generate random numbers in this range? (numbers should be very random i.e. every number should have equal probability to be selected)
Note:
long long int random=rand();
doesn't work as the number returned by rand
is int.
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.
这篇关于如何生成64位随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!