4

srand(time(0)) does not seem to be seeding rand() correctly, the 1st number generated is always the same.

This is running on OS X, is there something wrong with my settings or my code? I do wait a couple of seconds to rerun the program. The 1st number increments only a day later, the rest of the numbers are always random.

#include<iostream>
using namespace std;

int main ()
{
    int Num1,Num2;

    // seed the random number generator

    srand((unsigned int )time(NULL));

    Num1 = rand() %49 +1 ;

    do {Num2 = rand() % 49 + 1;}
    while(Num2 == Num1);

    ///Display Random Numbers

    cout<<"Numbers are: "<<endl;
    cout<<Num1<<" "<<Num2<<endl<<endl;

    return 0;
}
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
Visions23
  • 85
  • 7

3 Answers3

3

You are getting the same numbers because the seeds are so close in value and the random generator hasn't had time to diverge yet. On OS X use sranddev() instead of srand(), it will give you a better seed and avoid this problem.

#include<iostream>
using namespace std;

int main()
{
  int a, b;

  // seed the random number generator
  sranddev();

  a = rand();
  b = rand();

  cout << a << " " << (a % 49) + 1 << endl
       << b << " " << (b % 49) + 1 << endl << endl;

  return 0;
}
Variable Length Coder
  • 7,958
  • 2
  • 25
  • 29
  • sranddev() did the trick. Many thanks. I'l read up on the differences between srand and sranddev on OX. – Visions23 Dec 04 '14 at 19:52
  • 2
    On most modern POSIX systems `arc4random_uniform()` should be go to random generator, as it avoids both seeding and modulus bias. Only reason not to use it is if you need the higher performance of the lower quality generators. – Jon Shier Dec 04 '14 at 20:12
0

Assuming you have access to C++11, you would have better luck with something like this:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 50);
    std::cout << "Numbers are: " << dis(gen) << " " << dis(gen) << "\n";
    return 0;
}

rand is typically a pretty poor random generator with limited range of values and using % N to limit the values makes it even worse. There's a presentation about why rand isn't a good choice here: http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

Retired Ninja
  • 4,785
  • 3
  • 25
  • 35
  • Thank you for the responses so far, I'm still learning C++, (Information Systems Undergrad), i ran the code on an online compiler and it works, i'l try on codeblocks but the problem seems to be with xcode. – Visions23 Dec 04 '14 at 19:21
0

Besides using sranddev() instead of rand(). Increasing the range also form %49 to 50 or higher also seemed to work.

Visions23
  • 85
  • 7