Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Would I Make A Random Seed/Hash To Make Rand Actually Random? [duplicate]

Tags:

c++

random

how would i generate a seed or hash that would make rand actually random? I need it to change every time it picks a number. New to c++ so i'm not exactly sure how to do this. Thanks! :D

like image 248
ArcticWolf_11 Avatar asked Mar 29 '16 05:03

ArcticWolf_11


People also ask

How do you generate a random number in rands?

If you want to use RAND to generate a random number but don't want the numbers to change every time the cell is calculated, you can enter =RAND() in the formula bar, and then press F9 to change the formula to a random number.

How do I randomly generate a random seed in Python?

Python Random seed() Method The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time. Use the seed() method to customize the start number of the random number generator.

Is rand actually random?

However, the numbers generated by the rand() are not random because it generates the same sequence each time the code executed.

Why is rand () giving me the same number?

This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up. If you wish to generate different random values in each MATLAB session, you can use the system clock to initialize the random number generator once at the beginning of each MATLAB session.


2 Answers

With C++11 you can use std::random_device. I would suggest you to watch link for a comprehensive guide.

Extracting the essential message from the video link : You should never use srand & rand, but instead use std::random_device and std::mt19937 -- for most cases, the following would be what you want:

#include <iostream>
#include <random>
int main() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> dist(0,99);
    for (int i = 0; i < 16; i++) {
        std::cout << dist(mt) << " ";
    }
    std::cout << std::endl;
}
like image 89
Utkarsh Bhardwaj Avatar answered Sep 28 '22 23:09

Utkarsh Bhardwaj


There is no such thing as an "actually random" random number generator without sampling environmental data or accessing a quantum random number source. Consider accessing the ANU random number source if you require truly random numbers (http://qrng.anu.edu.au/FAQ.php#api).

Otherwise, Boost provides a more robust pseudo-RNG, which should suffice for most purposes: http://www.boost.org/doc/libs/1_58_0/doc/html/boost_random.html

like image 40
manglano Avatar answered Sep 28 '22 22:09

manglano