-2

Forgive me if it's obvious, but I'm having some trouble with the idea of generating a truly random integer in range, I've just started using C++. My current code:

int start = rand() % 30 + 20;

always results in 31, as this is a "psuedo-random" integer. It is also above 30! Can true random numbers be achieved in this way, and also, how can I actually generate a number in range?

-Jai

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • 1
    http://stackoverflow.com/questions/1108780/why-do-i-always-get-the-same-sequence-of-random-numbers-with-rand – πάντα ῥεῖ Nov 09 '14 at 14:50
  • You cannot get "a true random number" this way. To get a true random number you need a true random event. For example, elementary particle decay, white noise etc... – lapk Nov 09 '14 at 14:52

2 Answers2

4

A normal computer can only generate pseudo-random numbers,
but that does not mean that the generated numbers will be the same every time.
Your problem is that you forgot srand, that rand isn´t that good either way,
and that the formula should be (rand() % 10) + 20.

For better generators than rand, see eg. Mersenne Twister (include <random>).
For "true" random numbers, you need special hardware.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
  • (Side note: Capturing the input from a microphone, if done right, is a cheap "real" random source. But even a microphone isn´t built-in in every computer, and one could argue that the environment noise is predictable to a certain degree too). – deviantfan Nov 09 '14 at 15:02
  • There are much easier ways of getting randomness than that. Sites on the internet derive random numbers from natural phenomena that are random (like lightning strikes world wide). http://www.random.org/ – Martin York Nov 09 '14 at 15:33
  • It´s easier to get numbers from random.org in a C++ program at runtime than calling a method in ``? And in the case of security reasons, no internet (and no Mersenne twister) is good enough, even if the internet has perfect randomness. – deviantfan Nov 09 '14 at 15:39
  • Absolutely; Use the standard functions. I was just comparing your example of getting true randomness from a microphone. Which seems overly difficult (and easy to compromise) compared to other easier ways. – Martin York Nov 09 '14 at 15:47
1

In C++, you might do something like this:

#include <iostream>
#include <random>
#include <chrono>

class Rand_int {
public:
  Rand_int(int low, int high)
    : re(std::chrono::system_clock::now().time_since_epoch().count()),
      dist{low,high} { }
  int operator()() { return dist(re); }
private:
  std::default_random_engine re;
  std::uniform_int_distribution<> dist;
};


int main() {
  Rand_int rnd {20, 30};
  for (int i=0; i<10; i++)
    std::cout << rnd() << '\n';
  return 0;
}
ooga
  • 15,423
  • 2
  • 20
  • 21