Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

c++ - generate random 64 bit integer

I need your help and please give me some advice. From programming pearls I know that to generate random 30 bit integer we should write it like this:

RAND_MAX*rand()+rand()

But what could I do for generating not 30, but 64 bit random integer instead? I think that is very inefficient method if I multiply two 30 bit integers and then multiply again 4 bit integer, so what kind of method should I use? I am using now popcount_1 different method for 64 bit one and I would like to test it on random integers(I am also measuring the time which each one takes to accomplish the task)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, I have my doubts about the solution you post for a 30 bit integer. RAND_MAX itself could be a 31 bit value, and RAND_MAX * rand() + rand() is likely to overflow, producing undefined behavior (and in practice, negative values).

If you need a value larger than the guaranteed minimum of RAND_MAX, or for that matter, anything that isn't significantly smaller than RAND_MAX, the only solution will be to use successive calls to rand(), and combine the values, but you need to do this carefully, and validate the results. (Most implementations of rand() use linear congruent generators, which while adequate for some tasks, aren't particularly good in this case.) Anyway, something like:

unsigned 
rand256()
{
    static unsigned const limit = RAND_MAX - RAND_MAX % 256;
    unsigned result = rand();
    while ( result >= limit ) {
        result = rand();
    }
    return result % 256;
}

unsigned long long
rand64bits()
{
    unsigned long long results = 0ULL;
    for ( int count = 8; count > 0; -- count ) {
        results = 256U * results + rand256();
    }
    return results;
}

(The code in rand256 is designed to eliminate the otherwise unavoidable bias you get when mapping RAND_MAX values to 256 values.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...