Random number generation in c++ using GMP - c++

In java random number can get like
protected final static Random RANDOM = new Random(System.currentTimeMillis());
In c++ using GMP Library how it possible to generate random number?
I used code like
gmp_randstate_t s;
unsigned long seed;
seed = time(NULL);
gmp_randinit_default(s);
gmp_randseed_ui(s, seed);
mpz_class ran;
gmp_randclass rr(s);
ran =rr.get_z_bits(125);
long int random=ran.get_ui();
But i dont get random number.
Please help me.

First, there is no gmp_randclass constructor that takes a gmp_randstate instance, so your code didn't compile for me. The recommended way to construct a gmp_randclass instance is using gmp_randinit_default, like this:
gmp_randclass rr(gmp_randinit_default);
The first part of your code is seeding the gmp_randstate_t s, but that random state variable s is not used in the second part of your code (after the above change). Unless seeded otherwise, the default GMP random number generator always starts with the same seed, which means the same sequence of random numbers will be generated each time you run the program. You can seed an instance of gmp_randclass using the gmp_randclass::seed function.
The following code is similar to yours but seeds the random number generator based on the current time.
mpz_class ran;
gmp_randclass rr(gmp_randinit_default);
rr.seed(time(NULL));
ran =rr.get_z_bits(125);
long int random=ran.get_ui();
Note that as discussed in Random State Seeding, using a low-resolution current time is usually a poor choice for a random number generator seed.

Related

C++ random numbers are always the same

I am currently stuck at generating random numbers during runtime. In Java, I just call Math.random() and I'm pretty much done (I just need a simple RNG). In C++, I have tried several ways to generate random numbers and always end up getting the same.
Currently, I am using the following method to get a random number between MIN and MAX:
unsigned int getRandomNumber(int min, int max){
std::mt19937 mt(1729);
std::uniform_int_distribution<int> dist(min, max);
return dist(mt);
}
I have an object that calls this function in its constructor and assigns the value returned to an attribute. I currently create five instances of this object and the random number is always the same. Setting a big range (1 - 1000) does not change this. The number is always the same. Security is not a concern, it is an extremely simple application.
A random number generator works with a seed. Basically it's a number that's set only once for the random number generator to work with. If you re-seed your random number generator each time you try to generate an number you will get the same number every time. You should create the std::mt19937 object only once.
unsigned int getRandomNumber(int min, int max){
static std::mt19937 mt(1729);
std::uniform_int_distribution<int> dist(min, max);
return dist(mt);
}
Making mt static will cause it to only be instantiated once, which means it will only be constructed once, which means it will only be seeded once. Even with this fix, you'll still get the same series of numbers each time you run the program, but they'll be different each time you call getRandomNumber in one single execution.
A much better solution would be to instantiate the mt variable elsewhere, and pass it in to this function as a parameter, that way you could manage how it is seeded with more code than just a constructor call. Typically you would seed with a value based on time. Lots of insight here.

Random number generator repeats every time?

I'm trying to find a random number generator that will give me a single random number each time I run it. I have spent a week trying dozens of different ones, both from this site and others. Every time I run it, it gives me the same number! The only time it changes is if I change the range, and then it just gives me the new number over and over.
I am running Code::Blocks ver. 16.01 on Windows 7. Can anyone help?? I'm at my wits' end!
This code gives me a decently ramdom string of numbers, but still the same string each time!
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 eng(rd()); std::uniform_int_distribution<> distr(0, 10);
for(int n=0; n<100; ++n)
std::cout << distr(eng) << '\t';
}
I have tried the code on my compiler app on my phone as well.
Every pseudo random number generator will return the same sequence of numbers for the same initial seed value.
What you want to do is to use a different seed every time you run the program. Otherwise you'll just be using the same default seed every time and get the same values.
Picking good seeds is not as easy as you might think. Using the output from time(nullptr) for example still gives the same results if two copies of the program run within the same second. Using the value of getpid() is also bad since pid values wrap and thus sometimes you'll get the same value for different runs. Luckily you have other options. std::seed_seq lets you combine multiple bad sources and returns a good (or rather, pretty good) seed value you can use. There is also std::random_device which (on all sane implementations) returns raw entropy - perfect for seeding a pseudo random generator (or you can just use it directly if it is fast enough for your purpose) or you can combine it with std::seed_seq and the bad sources to seed a generator if you are worried it might be implemented as a prng on your implementation.
I would advice you to read this page: http://en.cppreference.com/w/cpp/numeric/random for an overview of how to deal with random number generation in modern C++.
The standard allows std::random_device to be implemented in terms of a pseudo-random number generator if there is no real random source on the system.
You may need to find a different entropy source, such as the time, or user touch co-ordinates.

Random generator for guess game

I've been searching for a better solution than my own and I haven't really been able to find one that I understand or that works for me.
I have made the simple game where the computer randomly generates a number which you then guess a number and if it is higher the computer says higher and so on..
The problem is my randomly generated number, after looking up alot of information regarding the <random>, uniform_int_distribution and default_random_engine. I have found out that the computer generates a random number, but if you run the program again the same random number will be generated.
My solution:
uniform_int_distribution<unsigned> u(0,100); // code to randomly generate numbers between 0 and 100
default_random_engine e; // code to randomly generate numbers
size_t userInput; // User input to find out where to look in the vector
vector<int> randomNumbers; //vector to hold the random numbers
unsigned start = 0, ending = 101, cnt = 0; // used in the game not important right now
cout << "Please enter a number between 1 and 1000 for randomness" << endl;
cin >> userInput;
for(size_t i = 0; i < 1000; ++i){ //for loop to push numbers into the vector
randomNumbers.push_back(u(e));
}
unsigned guess = randomNumbers[userInput]; // finally the number that the user will have to guess in the game
My solution right now is to use a vector where I push alot of randomly generated numbers in then ask the user to type a number which then the computer uses for the game. But there should be a better way of doing this. And my question is therefore
Is there a better way to randomly generate numbers to use in the game?
Either use std::random_device in place of std::default_random_engine, or else think of a way to provide a different number to the engine each time it is run.
This number is called a "seed" and can be passed as an optional parameter to the constructor. Since std::default_random_engine is implementation-specific, and different engines do different things about seeding, you generally want to choose a specific engine if you're providing a seed. A deterministic pseudo-random number generator will produce the same sequence of outputs for any given seed, so you want to use a different seed each time.
For no-security uses like a guessing game, the most "obvious" thing to use as a seed is the current time. Generally speaking this is different each time the program is run, although obviously if you can run the program twice in less than the granularity of the clock then that's not the case. So using the time to seed your random engine is pretty limited but will do the job for a toy program.
That's because your random number is actually what we call a pseudorandom number generator
It's just a machine that given a starting number generates a large list of seemingly random numbers. As you don't provide a starting number, the generated list of random numbers is thus always the same. One easy way to fix this is to use the current time as a starting value or 'seed', which is an argument of the constructor of std::default_random_engine.
You can also use your machines real random number generator std::random_device as a replacement for std::default_random_engine
Why not simply:
#include <ctime> // for time()
#include <cstdlib> // for srand()
srand(time(NULL)); // Initializes the rand() function
int randomNumber = rand()%100; // Random number between 0 and 99.
What this does is the rand() seed is set at the current time, meaning that every execution of the program will have a different seed for rand().
Still just pseudo-random solution, though suitable for your purposes.

default_random_engine isn't randomizing values for me

When I run my function my x and y values stay the same every time it is run. I'm not sure if I am using the default_random_engine incorrectly or not. How can I get my x and y values using the dist(engine) to randomize and not be the same output every time the program executes?
A 'seed' is something that provides a pseudonumber generator with its 'randomness'. If you initialise it with the same seed, you will get the same 'random' pattern.
Here, you are probably passing the same seed in all the time.
Maybe you should define your function like this instead:
long double fn( long reps, default_random_engine & engine )
Declare a single instance of your random number generator when you run your program, and seed it once with a value that will always be different when your program starts (eg the system time). Then, pass the generator into any functions that require random number generation.

Same random numbers every time I run the program

My random numbers that output, output in the same sequence every time I run my game. Why is this happening?
I have
#include <cstdlib>
and am using this to generate the random numbers
randomDiceRollComputer = 1 + rand() % 6;
You need to seed your random number generator:
Try putting this at the beginning of the program:
srand ( time(NULL) );
Note that you will need to #include <ctime>.
The idea here is to seed the RNG with a different number each time you launch the program. By using time as the seed, you get a different number each time you launch the program.
You need to give the randum number generator a seed. This can be done by taking the current time, as this is hopefully some kind of random.
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int r;
srand(time(0));
r = rand();
return 0;
}
The rand() function is specifically required to produce the same sequence of numbers when seeded with a given seed (by calling srand()); each possible seed value specifies a sequence. And if you never call srand(), you get the same sequence you would have gotten by calling srand(1) before any call to rand().
(This doesn't apply across different C or C++ implementations.)
This can be useful for testing purposes. If there's a bug in your program, for example, you can reproduce it by re-running it with the same seed, guaranteeing that (barring other unpredictable behaviors) you'll get the same sequence of pseudo-random numbers.
Calling srand(time(NULL)) is the usual recommended way to get more or less unpredictable pseudo-random numbers. But it's not perfect. If your program runs twice within the same second, you'll probably get the same sequence, because time() (typically) has a resolution of 1 second. And typical `rand() implementations are not good enough for cryptographic use; it's too easy for an attacker to guess what numbers you're going to get.
There are a number of other random number implementations. Linux systems have two pseudo-devices, /dev/random and /dev/urandom, from which you can read reasonably high-quality pseudo-random byte values. Some systems might have functions like random(), drand48(), and so forth. And there are numerous algorithms; I've heard good things about the Mersenne Twister.
For something like a game, where you don't expect or care about players trying to cheat, srand(time(NULL)) and rand() is probably good enough. For more serious purposes, you should get advice from someone who knows more about this stuff than I do.
Section 13 of the comp.lang.c FAQ has some very good information about pseudo-random number generation.
Pseudorandom number generators take a starting number, or seed, and then generate the next number in the sequence from this. That's why they're called pseudorandom, because if they always use the same starting value, they will generate the same sequence of numbers like the C standard lib generator does. This can be fixed by giving the generator a starting value that will change the next time the program is run like the current time.
Anyway, the code you're looking for like others have said is:
srand(time(0)); //Seed the generator, give it a starting value