111

Possible Duplicate:
Generate Random numbers uniformly over entire range

I want to generate the random number in c++ with in some range let say i want to have number between 25 and 63.

How can I have that?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
Abdul Samad
  • 5,748
  • 17
  • 56
  • 70

6 Answers6

357

Since nobody posted the modern C++ approach yet,

#include <iostream>
#include <random>
int main()
{
    std::random_device rd; // obtain a random number from hardware
    std::mt19937 gen(rd()); // seed the generator
    std::uniform_int_distribution<> distr(25, 63); // define the range

    for(int n=0; n<40; ++n)
        std::cout << distr(gen) << ' '; // generate numbers
}
Dmitri Nesteruk
  • 23,067
  • 22
  • 97
  • 166
Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • 55
    If you wonder "what the hack is `mt19937` type?!" - `A Mersenne Twister pseudo-random generator of 32-bit numbers with a state size of 19937 bits.` It is a "wrapper" for the "mersenne_twister_engine" template (http://www.cplusplus.com/reference/random/mersenne_twister_engine/) with pre-set params. – jave.web Nov 12 '14 at 11:56
  • I made a little I/O console app that asks for info and then dynamicly outputs the random numbers acordingly - http://ideone.com/wk239Q *BTW: modern C++ approach - +♥ ! * – jave.web Nov 12 '14 at 12:11
  • Downvote for the moment, as `std::random_device` returns the error `/home/akiva/Programming/Tutorial/tutorial/main.cpp:21: error: 'random_device' is not a member of 'std'` in my ubuntu 14.10 setup with qtcreator. Not sure if this a deprecated function, that it is not included in Linux, or if I am simply incompetent. – Anon Dec 31 '14 at 12:07
  • 7
    @Akiva I think, the last is correct. If it's absent from your distribution, you should upgrade your compiler to C++11-compliant one. It isn't a deprecated function, it's a new one. GCC 4.9+ should certainly have it. – polkovnikov.ph Jan 25 '15 at 00:41
  • 10
    Also worth noting that to do this same thing with floats/doubles, one can use std::uniform_real_distribution<>. Great answer! – David K. Jun 16 '15 at 20:10
  • 39
    Note the `std::uniform_int_distribution<>` is inclusive -- `[25,63]` in the above example. – BoltzmannBrain Sep 23 '16 at 04:20
  • 4
    @Akiva and @polkovnikov.ph: It's not about upgrading the compiler (GCC has had C++11 support for ages), but about switching to C++11 using the `-std=c++11` compiler flag. Since C++11 is not backwards compatible, all standard-complying compilers (GCC, clang,...) require C++11 to be activated explicitly. – mastov Oct 27 '16 at 12:34
  • could anybody explain how to put this stuff into class members without template overblowing and simply reuse the number generation on any place, like a loop or a callback function? [Here](https://cppbyexample.com/random_int.html) is a ref but only with globals – woodz May 03 '22 at 07:54
  • Thanks though it is incredible the hops one has to jump just to get a random integer in C++ in this day and age – gatopeich Oct 19 '22 at 11:44
  • @gatopeich that's why there's a proposal for https://en.cppreference.com/w/cpp/experimental/randint – Cubbi Oct 19 '22 at 23:06
50

You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:

25 + ( std::rand() % ( 63 - 25 + 1 ) )
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • 40
    Note that this answer *does not generate equally-likely numbers!* The below answer is a better approach. – George Hilliard Mar 28 '14 at 07:23
  • 1
    @GeorgeHilliard why? i really does not know, how the algorithm for generating random numbers work – milanHrabos Jul 29 '20 at 21:43
  • 10
    @milanHrabos an example will easily make that clear: `std::rand()` returns equally distributed integers from `0` to `RAND_MAX` (*inclusively*). Now, assuming you obtained integers in the range from `0` to `RAND_MAX - 1` (inclusively) by using `std::rand() % RAND_MAX`, the chance of getting a `0` would now be doubled, since it will be the result when `std::rand()` returns *either* `0` *or* `RAND_MAX`. Any other number will only be obtained when directly returned by `std::rand()`. This will apply similarly, for every modulo that is not a divisor of `RAND_MAX + 1`. – Reizo Aug 27 '20 at 14:29
  • 5
    @GeorgeHilliard "Below" is relative. – stackprotector Oct 22 '21 at 07:06
31
int range = max - min + 1;
int num = rand() % range + min;
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • 6
    Bad advice. This will not yield a uniform distribution. It is a fairly common approach though (but fundamentally flawed). – Johannes Rudolph Sep 26 '11 at 19:23
  • Why is this flawed? If `rand() % range` is relatively uniform, I would expect that adding a constant would preserve uniformity. Or are you saying that `rand()` itself isn't a great choice for a truly random number? That's true, but depending on what OP wants to do, rand() may be sufficient. – Anson Sep 26 '11 at 19:32
  • @Johannes: I think [this is uniform enough](http://ideone.com/y6m8o) for most peoples purposes unless they specifically mention perfect uniformity as a requirement. – Benjamin Lindley Sep 26 '11 at 19:40
  • adding a constant will not preserve uniformity when range is large. However, for most applications this is uniform enough. – Mooing Duck Sep 26 '11 at 19:42
  • 12
    @Anson: The reason that `Johannes Rudolph` is complaining is that % does not work unless the value on the right is an exact divisor of RAND_MAX. If it is not then some values have a slight (very slight) smaller probability. example: RAND_MAX (32767) `r = rand()%3;` Probability of 0(10923/32767) 1(10922/32767) 2(10922/32767) Notice the probability of a 0 is slightly higher. As 'Benjamin Lindley' points out this is insignificant in most situations but when you do things like cryptography things like this become a problem. Thus a lot of people cry foul when this method is used. – Martin York Sep 26 '11 at 20:25
  • 3
    Also there was a problem with the bottom few bits of rand() not being very random (thus if max-min is small you don't get good values (this may have been fixed)). The alternative being `num = rand() * 1.0 / RAND_MAX * (max-min+1) + min;` – Martin York Sep 26 '11 at 20:29
  • 1
    @MartinYork your alternative is no better, it still suffers from the pigeonhole problem, it's just not as obvious why. – Mark Ransom May 08 '21 at 18:37
30
int random(int min, int max) //range : [min, max]
{
   static bool first = true;
   if (first) 
   {  
      srand( time(NULL) ); //seeding for the first time only!
      first = false;
   }
   return min + rand() % (( max + 1 ) - min);
}
Pavan Manjunath
  • 27,404
  • 12
  • 99
  • 125
Nawaz
  • 353,942
  • 115
  • 666
  • 851
10

Use the rand function:

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

Quote:

A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014
Kiley Naro
  • 1,749
  • 1
  • 14
  • 20
  • 1
    @Tux-D That was a code snippet copied straight from the cplusplus website so I guess I figured it was the standard way of doing it. I didn't realize it was incorrect or uncommon to do this way, thanks for the info. Because now I'm curious, what exactly is the problem with this method? – Kiley Naro Sep 27 '11 at 02:15
  • See `Benjamin Lindley` answer above and my associated comments for the pre-C++11 approach. But my comment above was wrong (I miss read your answer). So I will delete it. The website cplusplus.com is OK bit I (and good for quick reference now and then) but I would NOT use it as an authoritative source. – Martin York Sep 27 '11 at 03:49
  • Thanks for the information. I read the information above and feel I have a better understanding. I would argue that while my answer isn't the best possible answer, it's not NOT useful. But that's your decision and I thank you again for enlightening me. :) – Kiley Naro Sep 27 '11 at 13:18
  • 3
    See: http://www.azillionmonkeys.com/qed/random.html – Martin York Sep 27 '11 at 15:32
3
float RandomFloat(float min, float max)
{
    float r = (float)rand() / (float)RAND_MAX;
    return min + r * (max - min);
}
Yurii Hohan
  • 4,021
  • 4
  • 40
  • 54