How to Generate Random Numbers in C++ Using `<random>`?

  • Context: Comp Sci 
  • Thread starter Thread starter anonim
  • Start date Start date
  • Tags Tags
    C++ Numbers Random
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
anonim
Messages
39
Reaction score
2
Homework Statement
-
Relevant Equations
-
I want to generate random numbers in C++. I do not want to use C library function (`<cstdlib> <ctime> (time.h)` ) and class. So I cannot use `rand()` function in C. I want to generate random integer numbers and I guess I can use `<random>` library in C++11. How can I use this generate random numbers?
 
on Phys.org
There is no reason that you have to use ctime to use the C-library rand(). Some examples use ctime to get a changing initial seed for an initial call to rand()'s srand() initialization function. You do not need to use that. You can set an initial seed using an unsigned integer of your choice in srand().

I have always assumed that the C++ version actually used the C rand().
 
anonim said:
How can I use this generate random numbers?

The documentation has examples. If you've already looked at them and need more help, please say so, what you've tried, what isn't working and where exactly you want help.

FactChecker said:
I have always assumed that the C++ version actually used the C rand().

It does not. One selects the RNG, and has many choices.
 
Vanadium 50 said:
It does not. One selects the RNG, and has many choices.
You might be right, but that is not very convincing. One often calls a pseudorandom number generator with a range of [0,1] and then converts the output to other ranges and distributions.
 
anonim said:
I want to generate random integer numbers and I guess I can use `<random>` library in C++11. How can I use this generate random numbers?

The classes in <random> are not super easy to use unless you know what you are doing, both regarding C++ and regarding the statistics your are trying to achieve, but once you got that they are quite flexible in allowing you to construct generators with all sorts of distributions. Since this is a homework question I would recommend you peek at the <random> API description with one eye and search for a good guide on the net with the other, and then return here with specific questions if you get stuck at some details.