Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does modulus and rand() work?

Tags:

c++

random

So, I've been nuts on this.

rand() % 6 will always produce a result between 0-5.

However when I need between, let's say 6-12.

Should I have rand() % 6 + 6

0+6 = 6.
1+6 = 7.
...
5+6 = 11. ???

So do I need to + 7 If I want the interval 6-12? But then, 0+7 =7. When will it randomize 6?

What am I missing here? Which one is the correct way to have a randomized number between 6 and 12? And why? It seems like I am missing something here.

like image 835
John Avatar asked Sep 20 '26 19:09

John


2 Answers

If C++11 is an option then you should use the random header and uniform_int_distrubution. As James pointed out in the comments using rand and % has a lot of issues including a biased distribution:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;

    std::mt19937 e2(rd());

    std::uniform_int_distribution<int> dist(6, 12);

    for (int n = 0; n < 10; ++n) {
            std::cout << dist(e2) << ", " ;
    }
    std::cout << std::endl ;
}

if you have to use rand then this should do:

rand() % 7 + 6

Update

A better method using rand would be as follows:

6 + rand() / (RAND_MAX / (12 - 6 + 1) + 1)

I obtained this from the C FAQ and it is explained How can I get random integers in a certain range? question.

Update 2

Boost is also an option:

#include <iostream>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>

int main()
{
  boost::random::mt19937 gen;
  boost::random::uniform_int_distribution<> dist(6, 12);

  for (int n = 0; n < 10; ++n) {
    std::cout << dist(gen) << ", ";
  }
  std::cout << std::endl ;
}
like image 161
Shafik Yaghmour Avatar answered Sep 23 '26 07:09

Shafik Yaghmour


You need rand() % 7 + 6.

Lowest number from rand() %7: 0. Highest number from rand() %7: 6.

0 + 6 = 6. 6 + 6 = 12.

like image 45
KlaFier Avatar answered Sep 23 '26 09:09

KlaFier