How to generate 64 bit random numbers? - c++

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.

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

Related

How to avoid same sequences of random numbers

I would like to generate different sequences of uniformly distributed samples. To this end, I initialize the default random engine with different seeds, but the same sequences are produced:
#include <iostream>
#include <random>
void fun(double seed)
{
std::cout << "given seed: " << seed << std::endl;
std::default_random_engine gen_2(seed);
std::uniform_real_distribution<double> dis_2(0.0,1.0);
std::cout << dis_2(gen_2) << std::endl;
std::cout << dis_2(gen_2) << std::endl;
}
int main()
{
double seed = 1.0;
std::default_random_engine gen_1(seed);
std::uniform_real_distribution<double> dis_1(0.0,1.0);
for(size_t i=0; i<3; ++i)
{
fun(dis_1(gen_1));
}
}
The output reads:
given seed: 0.0850324
0.0850324
0.891611
given seed: 0.891611
0.0850324
0.891611
given seed: 0.18969
0.0850324
0.891611
How can I produce different sequences in the function fun?
The seed of the generator is an integer.
The problem is that all numbers generated by your dis_1 are less than 1, and greater than or equal to 0. Therefore they implicitly convert to the same value 0 when converted to an integer.
The solution is to use a different seed, rather than 0 always.

random_shuffle and srand() give me the same result every time

I'm trying to produce do some processing on a random permutation of the alphabet, however each permutation produces the same result despite using srand(myseed)
I have included the <algorithm> header.
string create_permutation(unsigned seed)
{
srand(seed);
string permutation = ALPHABET;
random_shuffle(permutation.begin(), permutation.end());
return permutation;
}
cout << create_permutation(2) << endl; // or 3, 4, 5 etc
// continuously returns 'XQACKHSLOJ,TRBZNGV.W FIUEYDMP
Any help would be greatly appreciated.
EDIT: Minimal, Complete, and Verifiable example
EDIT 2: adjustment to mcve
#include <iostream>
#include <algorithm>
using namespace std;
const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,' ";
string create_permutation(unsigned seed)
{
srand(seed);
string permutation = ALPHABET;
random_shuffle(permutation.begin(), permutation.end());
return permutation;
}
int main(){
cout << create_permutation(2) << endl; // or 3, 4, 5 etc
// continuously returns 'XQACKHSLOJ,TRBZNGV.W FIUEYDMP
return 0;
}
The problem
The shuffles aren't random because shuffle_random is using the same seed for the random number generator each time it is called.
srand does not seed the random_shuffle function, it seeds rand and random_shuffle usually calls rand, but does not have to.
random_shuffle has two forms:
One that takes 2 arguments (begin/end iterators)
One that takes 3 (begin/end iterator and a random generator).
You have demonstrated that you know how to use the first form, but the problem with the first form is that it is implemented differently on different platforms and with different compilers. It may not use rand() at all, which is the function that srand seeds.
You should use the 3 argument form and provide the random number generator as a parameter to the function.
You can follow this detailed answer to learn how to make your own random number generator, or you can provide rand() to the random_shuffle function as the random number generator.
When you seed the random number generator, you set the starting point for an algorithm that will provide a sequence of psuedorandom numbers. If you always use the same seed, the algorithm will always have the same starting point and always generate the same sequence of numbers.
Every time you call srand, you reset the seed and reset the starting point for the algorithm.
A common bug here is to repeatedly call srand. Unless you have a very good reason not to (and if you do, you probably shouldn't use rand and srand at all. Look to the <random> library) you should call srand once at the beginning of the program to seed the generator once and ever after use that seed.
srand is also quite expensive. From a performance standpoint, you don't want to call it often.
So: since every call to create_permutation calls srand with the seed parameter and create_permutation is always called with the same seed value, for a given implementation of the random number generator, create_permutation will always use the same random number sequence and thus generate the same permutation.
A quick example that will generate different permutations, so long as the program is not run more often than once per second is
#include <iostream>
#include <string>
#include <algorithm>
#include <ctime>
const std::string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,' ";
std::string create_permutation()
{
std::string permutation = ALPHABET;
std::random_shuffle(permutation.begin(), permutation.end());
return permutation;
}
int main(){
srand(time(NULL)); // caveat: time's minimum resolution is 1 second.
// multiple executions of this program within 1
// second will get the same time and use the same seed.
std::cout << create_permutation() << std::endl;
std::cout << create_permutation() << std::endl;
std::cout << create_permutation() << std::endl;
std::cout << create_permutation() << std::endl;
std::cout << create_permutation() << std::endl;
return 0;
}
A more modern approach:
#include <random>
#include <algorithm>
#include <iostream>
#include<string>
const std::string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,' ";
std::random_device rd; // Warning: implementation of this is allowed to be stupid and
// return the same value every time. Does not work in mingw 4.8
// Can't speak for 4.9 or greater
std::mt19937 randomizer(rd());
std::string create_permutation()
{
std::string permutation = ALPHABET;
std::shuffle(permutation.begin(), permutation.end(), randomizer);
return permutation;
}
int main()
{
std::cout << create_permutation() << std::endl;
std::cout << create_permutation() << std::endl;
std::cout << create_permutation() << std::endl;
std::cout << create_permutation() << std::endl;
std::cout << create_permutation() << std::endl;
}

How to create random Gaussian vector in c++?

I'm trying to figure out how to generate a random Gaussian vector in c++. Would it be sufficient to generate random gaussian numbers and putting them in a vector?
EDIT: I just realized you were, probably, talking about multivariate Gaussian distribution. In this case, I think, you'd need N normal distributions, each corresponding to an univariate distribution along one of the coordinates. Then, you generate random vector's coordinates by sampling each of the distributions. Effectively, the edited code below represents coordinates of 10 two-dimensional random vectors, using C++11 pseudo-random number generation (code on ideone.com). Note, in the example given there will be correlation between the two coordinates, since there is correlation between consecutive pseudo-random numbers. One can try using two seeds with two generators with more sophisticated algorithms provided by the Standard library. However, I feel, there still might be a correlation, even using two different generators - one would have to investigate this issue to give a definite answer.
#include <iostream>
#include <vector>
#include <random>
#include <iomanip>
int main()
{
std::random_device device_random_;
std::default_random_engine generator_(device_random_());
std::normal_distribution<> distribution_x_(1.0, 0.5);
std::normal_distribution<> distribution_y_(10.0, 1.0);
std::vector<double> vector_x_, vector_y_;
for (int counter_(0); counter_ < 10; ++counter_)
{
vector_x_.push_back(distribution_x_(generator_));
vector_y_.push_back(distribution_y_(generator_));
std::cout << std::fixed << std::setprecision(4) << "(" << vector_x_[counter_]
<< ", " << vector_y_[counter_] << ")\n";
}
return (0);
}
Program output:
(0.2390, 10.3887)
(1.1087, 9.5847)
(1.0920, 9.3468)
(1.1982, 11.6633)
(0.8840, 11.0903)
(0.5573, 8.5121)
(0.6709, 11.4706)
(1.1477, 9.4374)
(0.8778, 11.0323)
(0.8255, 9.7704)
Boost.Random includes a normal distribution generator. You should be able to use this to populate a vector. Complete tested example code:
#include <boost/random/random_device.hpp>
#include <boost/random/normal_distribution.hpp>
#include <vector>
int main()
{
boost::random::random_device rng;
boost::random::normal_distribution<> generator(0, 100);
std::vector<int> vec;
vec.reserve(100);
std::generate_n(
std::back_inserter(vec),
100,
[&] () { return generator(rng); });
for (auto i : vec)
std::cout << i << ',';
return 0;
}

How to get current seed from C++ rand()?

I generate a few thousand object in my program based on the C++ rand() function. Keeping them in the memory would be exhaustive. Is there a way to copy the CURRENT seed of rand() at any given time? This would give me the opportunity to store ONLY the current seeds and not full objects. (thus I could regenerate those objects, by regenerating the exact same sub-sequences of random numbers)
An exhaustive solution is storing the full sequence of random numbers given by rand() - doesn't worth it.
Another would be solution is to implement my own class for randomized numbers.
Google gave me no positive clues. There are hundreds of articles teaching the basics of rand and srand, and I couldn't find the specific ones.
Does anyone know other random number generators with implemented seed-stealer?
Thank you for your fast answers! There are more possible answers/solutions to this question, so I made a list of your answers here.
SOLUTIONS:
The short answer is: there is no standard way to get the seed
The closest possible workaround is to save the INITIAL seed in the beginning, and count how many times you call the rand() function. I marked this as solution because it works on the current std::rand() function of every compiler (and this was the main question about). I've benchmarked my 2.0 GHz CPU, and found that I can call&count rand() 1,000,000,000 times in 35 seconds. This might sound good, but I have 80,000 calls to generate one object. This restricts the number of generations to 50,000 because the size of unsigned long. Anyway, here is my code:
class rand2
{
unsigned long n;
public:
rand2 () : n(0) {}
unsigned long rnd()
{
n++;
return rand();
}
// get number of rand() calls inside this object
unsigned long getno ()
{
return n;
}
// fast forward to a saved position called rec
void fast_forward (unsigned long rec)
{
while (n < rec) rnd();
}
};
Another way is to implement your own Pseudo-random number generator, like the one Matteo Italia suggested. This is the fastest, and possibly the BEST solution. You're not restricted to 4,294,967,295 rand() calls, and don't need to use other libraries either. It's worth mentioning that different compilers have different generators. I've compared Matteo's LCG with rand() in Mingw/GCC 3.4.2 and G++ 4.3.2. All 3 of them were different (with seed = 0).
Use generators from C++11 or other libraries as Cubbi, Jerry Coffin and Mike Seymour suggested. This is the best idea, if you're already working with them.
Link for C++11 generators: http://en.cppreference.com/w/cpp/numeric/random
(there are some algorithm descriptions here too)
Does anyone know other random number generators with implemented seed-stealer
All standard C++11 random number generators (also available in TR1 and in Boost) offer this functionality. You can simply copy the generator objects or serialize/deserialize them.
There's no standard way to obtain the current seed (you can only set it via srand), but you can reimplement rand() (which is usually a linear congruential generator) by yourself in a few lines of code:
class LCG
{
private:
unsigned long next = 1;
public:
LCG(unsigned long seed) : next(seed) {}
const unsigned long rand_max = 32767
int rand()
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}
void reseed(unsigned long seed)
{
next = seed;
}
unsigned long getseed()
{
return next;
}
};
Use srand() to set the seed. save the value you used as the seed.
http://cplusplus.com/reference/clibrary/cstdlib/srand/
The random number generation classes in C++11 support operator<< to store their state (mostly the seed) and operator>> to read it back in. So, basically, before you create your objects, save the state, then when you need to re-generate same sequence, read the state back in, and off you go.
rand() does not offer any way to extract or duplicate the seed. The best you can do is store the initial value of the seed when you set it with srand(), and then reconstruct the whole sequence from that.
The Posix function rand_r() gives you control of the seed.
The C++11 library includes a random number library based on sequence-generating "engines"; these engines are copyable, and allow their state to be extracted and restored with << and >> operators, so that you can capture the state of a sequence at any time. Very similar libraries are available in TR1 and Boost, if you can't use C++11 yet.
Is there a way to copy the CURRENT seed of rand() at any given time?
What follows is an implementation-specific way to save and restore the pseudo-random number generator (PRNG) state that works with the C library on Ubuntu Linux (tested on 14.04 and 16.04).
#include <array>
#include <cstdlib>
#include <iostream>
using namespace std;
constexpr size_t StateSize = 128;
using RandState = array<char, StateSize>;
void save(RandState& state) {
RandState tmpState;
char* oldState = initstate(1, tmpState.data(), StateSize);
copy(oldState, oldState + StateSize, state.data());
setstate(oldState);
}
void restore(RandState& state) {
setstate(state.data());
}
int main() {
cout << "srand(1)\n";
srand(1);
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << "srand(1)\n";
srand(1);
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << "save()\n";
RandState state;
save(state);
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << "restore()\n";
restore(state);
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
cout << " rand(): " << rand() << '\n';
}
This relies on:
the same PRNG being used by the C library to expose both rand() and random() interfaces, and
some knowledge about the default initialization of this PRNG in the C library (128 bytes state).
If run, this should output:
srand(1)
rand(): 1804289383
rand(): 846930886
rand(): 1681692777
rand(): 1714636915
rand(): 1957747793
rand(): 424238335
rand(): 719885386
rand(): 1649760492
srand(1)
rand(): 1804289383
rand(): 846930886
rand(): 1681692777
rand(): 1714636915
save()
rand(): 1957747793
rand(): 424238335
rand(): 719885386
rand(): 1649760492
restore()
rand(): 1957747793
rand(): 424238335
rand(): 719885386
rand(): 1649760492
This solution can help in some cases (code that can't be changed, reproducing execution for debugging purpose, etc...), but it is obviously not recommended as a general one (e.g. use C++11 PRNG which properly support this).
You could try saving the value that you used to seed right before (or after) the srand.
So, for example:
int seed = time(NULL);
srand(time(NULL));
cout << seed << endl;
cout << time(NULL);
The two values should be the same.
I would recommend you to use the Mersenne Twister Pseudo-Random Number Generator. It is fast and offer very good random numbers. You can seed the generator in the constructor of the class very simply by
unsigned long rSeed = 10;
MTRand myRandGen(rSeed);
Then you just need to store somewhere the seeds you used to generate the sequences...

Program is generating same random numbers on each run? [duplicate]

This question already has answers here:
Why does rand() yield the same sequence of numbers on every run?
(7 answers)
Closed 5 years ago.
I just finished coding a Minesweeper type game, and everything's good except for that each time I run the application, it generates the same number (I ran it 3 different times, saved the output to 3 text files and used the diff command in Linux, it didn't find any differences). It's seeded by time(NULL) so it should change every time, right?
Here's my code:
main.cpp
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <string>
#include "Minesweeper/box.h"
#include <cstdio>
int main(int argc, char** argv){
using namespace std;
bool gameOver = false;
int x, y, score = 0;
const int HEIGHT = 10;
const int WIDTH = 10;
unsigned int Time = time(0);
cout << "Welcome to Minesweeper. " << endl;
//setup grid
Box grid[10][10];
for(int i = 0; i < WIDTH; i++)
for(int n = 0; n < HEIGHT; n++){
unsigned int value = rand() %100 + 1;
cout << value << endl;
if(value <= 38){
grid[i][n].setFill(MINE);
//cout << i << "," << n << " is mined." << endl;
}
else
grid[i][n].setFill(EMPTY);
}
for(int r = 0; r < WIDTH; r++)
for(int l = 0; l < HEIGHT; l++)
if(grid[r][l].getFill() == EMPTY)
cout << r << "," << l << " - EMPTY." << endl;
else if (grid[r][l].getFill() == MINE)
cout << r << "," << l << " - MINE." << endl;
while(!gameOver){
cout << "Enter coordinates (x,y): ";
scanf("%i,%i",&x,&y);
if(grid[x][y].getFill() == MINE)
gameOver = true;
else{
cout << "Good job! (You chose " << x << "," << y << ")" << endl;
score++;
}
}
cout << "You hit a mine! Game over!" << endl;
cout << "Final score: " << score << endl;
getchar();
return EXIT_SUCCESS;
}
It's seeded by time(NULL)
If it is, I can't see it. In fact, a search for it in your code returns nothing. The default behaviour, if you don't explicitly seed, is the same as if you had seeded it with the value 1.
You need to explicitly state something like:
srand (time (NULL));
at the start of main somewhere (and make sure you do this once and once only).
Though keep in mind this makes it dependent on the current time - if you start multiple jobs in the same second (or whatever your time resolution is), they'll start with the same seed.
From the C standard (on which C++ is based for these compatibility features):
The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.
You need to seed randomizer. Call srand() at the beginning.
To add to the answers by others, you can use the Mersenne Twister Algorithm, which is a part of the C++11 library. Its fast becoming a standard in many common softwares to generate random numbers.
For example, this is the function I wrote, which I use often to generate random numbers in my other codes:
std::vector<double> mersennetwister(const int& My,const int& Mz,
const int& Ny,const int& Nz)
{
int ysize = (My + 2*Ny + 1);
int zsize = (Mz + 2*Nz + 1);
int matsize = ysize*zsize;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
// Seeding the generator with the system time
std::mt19937_64 generator (seed);
// Calling the Mersenne-Twister Generator in C++11
std::uniform_real_distribution<double> distribution(0,1);
// Specifying the type of distribution you want
std::vector<double> randarray(matsize,0);
// Saving random numbers to an array
for (int i=0;i<matsize;++i)
{
randarray[i] = distribution(generator); // Generates random numbers fitting the
// Distribution specified earlier
}
return(randarray);
}
Bottomline: C++11 has some excellent features for numerical operations and it would be a good idea to look into them. As for the Mersenne Twister, http://en.wikipedia.org/wiki/Mersenne_twister