Welcome
Welcome to the forums of AntiRTFM's Absolute N00b Spoonfeed C++ Tutorials!

You are currently viewing our boards as a guest, which gives you limited access to view most discussions and access our other features. By joining our free community, you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content, and access many other special features. Registration is fast, simple, and absolutely free, so please, <a href="/profile.php?mode=register">join our community today</a>!

Random Number Generator

Display your little helpful snippets of code that may help us all get something done

Random Number Generator

Postby antiRTFM on Mon May 12, 2008 3:29 pm

First,
Code: Select all
#include <ctime>
#include <cmath>


Now, before ever using the random number function, you need to call the following function at the beginning of your program (like at the beginning of main):

Code: Select all
srand((long)time(0));



Now you can go ahead and call the random number function. The basic c++ random number generator function is rand(), but it needs some more code to help it give you good results.

Here is a function definition that will generate a number inside a given range (you may want to copy this function as-is to your source code):

Code: Select all
int GetRand(int rangeMin, int rangeMax)
{
    return (int)floor(rand() / (RAND_MAX + 1.0) * ((rangeMax - rangeMin) + 1) + rangeMin);
}



Anytime you need a random number inside a range (like a random number from 5 to 47) just call GetRand(5, 47);
User avatar
antiRTFM
Administrator
 
Posts: 467
Joined: Sun Apr 13, 2008 9:10 am

Random number.

Postby Marss++ on Sat Jul 19, 2008 8:08 pm

I know this is the snippets section but I just wanted to give an example.
Here is an actual example of a random number generator. I commented it so that it woud be easier to understand. Its pretty basic.

Code: Select all

// RANDOM NUMBER GENERATOR
#include <iostream>
#include <time.h>
using namespace std;



int random_num(int n);  //Declaring random number generator function



int main()
{
   int n, i, r; // Need three integers
   cout << "Random number from 0 to 100" << endl; 
   cout << "Enter number of times to get random number" << endl;
   cin >> n;



   /* For loop. starts at 1 and goes untill the number
   you inputed. Each time the loop executes it gets a random
   number from 0 to 100 and prints it out
   */


   for (i = 1; i <= n; i++)
   {
      r = random_num(100) + 1; // Zero offset. the (+ 1) makes it 1 - 100 instead of 0 - 99

      cout << r << endl; //printing it out
   }
   return 0;
}

//Defining the random number generator
int random_num(int n)
{
   return rand() % n;
}




Any questions just pm me or reply.
Marss++
 
Posts: 149
Joined: Fri Jul 18, 2008 3:20 pm

Re: Random Number Generator

Postby Koeienboei on Sat May 02, 2009 4:20 pm

Still don't get it, can u give me an exemple how to make a random number between 1 and 10? :roll:
User avatar
Koeienboei
 
Posts: 11
Joined: Fri May 01, 2009 12:42 pm
Location: Holland

Re: Random Number Generator

Postby antiRTFM on Sun May 03, 2009 1:20 am

i've edited the original snippet code

follow the instructions exactly and you'll get it
User avatar
antiRTFM
Administrator
 
Posts: 467
Joined: Sun Apr 13, 2008 9:10 am

Re: Random Number Generator

Postby Koeienboei on Sun May 03, 2009 2:07 pm

Sweet :) thanks :roll:
User avatar
Koeienboei
 
Posts: 11
Joined: Fri May 01, 2009 12:42 pm
Location: Holland

Re: Random Number Generator

Postby Koeienboei on Sun May 03, 2009 2:15 pm

Hmm i get an error on this prog:

Code: Select all
#include "stdafx.h"
#include <iostream>
#include <ctime>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
   for(;;)
       {
                 srand((long)time(0));
                 cout << GetRand(0, 1);
        }
   return 0;
}


error C3861: 'GetRand': identifier not found

:O
User avatar
Koeienboei
 
Posts: 11
Joined: Fri May 01, 2009 12:42 pm
Location: Holland

Re: Random Number Generator

Postby NOOB on Sun May 03, 2009 2:25 pm

You have to declare and define the GetRand function;)
NOOB
 
Posts: 59
Joined: Tue May 06, 2008 11:04 am

Re: Random Number Generator

Postby antiRTFM on Sun May 03, 2009 3:21 pm

as mentioned, read and follow instructions exactly
User avatar
antiRTFM
Administrator
 
Posts: 467
Joined: Sun Apr 13, 2008 9:10 am

Re: Random Number Generator

Postby Koeienboei on Sun May 03, 2009 4:28 pm

oh im sorry, i thought that was in the ctime file or something.

but next problem :), i only get zeros...

Code: Select all
#include "stdafx.h"
#include <iostream>
#include <ctime>

using namespace std;

int GetRand(int rangeMin, int rangeMax)
{
    return (int)(rand() / (RAND_MAX + 1.0) * (rangeMax - rangeMin) + rangeMin);
}

int _tmain()
{
   for(;;)
   {   
      srand((long)time(0));
      cout << GetRand(0, 1);
   }
   return 0;
}



i now in the language pascal u need to type "randomize" before each random function, is this the same with the srand((long)time(0));?

or is something else wrong?
User avatar
Koeienboei
 
Posts: 11
Joined: Fri May 01, 2009 12:42 pm
Location: Holland

Re: Random Number Generator

Postby antiRTFM on Sun May 03, 2009 4:51 pm

hm cool! you've found a flaw in the code!

working on this...

BTW call srand() just once at the very beginning of the program
User avatar
antiRTFM
Administrator
 
Posts: 467
Joined: Sun Apr 13, 2008 9:10 am

Re: Random Number Generator

Postby antiRTFM on Sun May 03, 2009 5:50 pm

aight patched it up

lets see how well this version works

next update would be to handle if rangeMin is more than rangeMax
User avatar
antiRTFM
Administrator
 
Posts: 467
Joined: Sun Apr 13, 2008 9:10 am

Re: Random Number Generator

Postby antiRTFM on Sun May 03, 2009 6:11 pm

and here it is

*EDITED*
Code: Select all
int GetRand(int num1, int num2)
{
    int & rangeMin = num1 > num2 ? num2 : num1;
    int & rangeMax = num1 > num2 ? num1 : num2;
    return (int)floor(rand() / (RAND_MAX + 1.0) * ((rangeMax - rangeMin) + 1) + rangeMin);
}


now you do GetRand(0, 22) or GetRand(22, 0) and youl have same results. whereas in the previous version, if you'd enter GetRand(22,0) youd get weird results. this is useful when you may not know which one is at the top of the desired range and which is at the bottom
User avatar
antiRTFM
Administrator
 
Posts: 467
Joined: Sun Apr 13, 2008 9:10 am

Re: Random Number Generator

Postby Koeienboei on Mon May 04, 2009 3:57 pm

Hmmkay... next problem, maybe this doesnt fit in this thread...

Code: Select all
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cmath>
#include <string>

using namespace std;

int GetRand(int rangeMin, int rangeMax)
{
    return (int)floor(rand() / (RAND_MAX + 1.0) * (rangeMax - rangeMin) + rangeMin + 0.5);
}

int _tmain()
{
   srand((long)time(0));
   string line;
   char number;

   for(;;)
   {   
      for(int x = 0; b++ < 20;)
      {      
         if GetRand(0, 1) = 0
            number = '0';
         else
            number = '1';
         
         line += number;
      }
      
      cout << a + "/n";
   }
   return 0;
}


i want to make a line of zeros and ones, so i add 20 numbers to the string 'line'. Then i add /n, so i go to the next line and do it all again so i get a matrix sort of thingy :).

But i get smilies :O. Probebly the code for a smily is 1, but i want to add a number not a smilie. How do i do this?
User avatar
Koeienboei
 
Posts: 11
Joined: Fri May 01, 2009 12:42 pm
Location: Holland

Re: Random Number Generator

Postby antiRTFM on Mon May 04, 2009 4:05 pm

for that you need to convert from the integer number 0-1 to the characters '0' and '1'

have a look here and here

(or here)
User avatar
antiRTFM
Administrator
 
Posts: 467
Joined: Sun Apr 13, 2008 9:10 am

A "Better" Random Number Generator

Postby yellowaeroplane on Mon Jun 15, 2009 9:39 pm

Hey there,

First of all, thank you very very much for your time and contributions antiRTFM. People like you are truly what make this crazy world a better place.

Onward though...

Let me first point out that I am by no means an expert C++ coder. I've been working with PHP, Python, and Ruby for a few years and I finally just decided to start tackling a compiled language. I stumbled upon your fantastic tutorials and to make a long story short, that's why I'm here.

I'd just like to alert you to a minor flaw in your original random number function(s). Take for example the following code which acts as a 'lottery,' by picking a lucky winner out of an array of ten contestants. I'm going to repeat the 'drawing' 10000 times and keep track of how many times each contestant wins. In an ideal world, using a perfect random number generator, each contestant should win roughly 1000 times each (1000 * 10 = 10000):

Code: Select all
#include <iostream>
#include <cstdlib> //This header was missing from your example... but probably since I'm using Linux.
#include <cmath>
#include <ctime>
#include <string>

using namespace std;

int GetRand(int rangeMin, int rangeMax) {
    return (int)floor(rand() / (RAND_MAX + 1.0) * (rangeMax - rangeMin) + rangeMin + 0.5 );
}

int main() {
      srand((long)time(0));
      string names[10] = {"John","Brad","Jose","Nick","Tom","Chris","Zach","Matt","George","Steve"};
      int wins[10] = {0,0,0,0,0,0,0,0,0,0};
      int i = 0;
      int winner;
      do {
            winner = GetRand(0,9); //using your GetRand() function to pick a winner
            wins[winner]++; //keep track of this win
            i++;
      } while (i < 10000);
      i = 0;
      do {
            cout << names[i] << " won " << wins[i] << " times." << endl;
            i++;
      } while (i < 10);
      return 0;
}


However, this result (or something similar) will be returned:

John won 537 times.
Brad won 1107 times.
Jose won 1116 times.
Nick won 1158 times.
Tom won 1076 times.
Chris won 1170 times.
Zach won 1125 times.
Matt won 1070 times.
George won 1085 times.
Steve won 556 times.

As you'll notice, contestants 2-9 have very similar (and expected) results, while contestants 1 and 10 have roughly 1/2 the 'wins' as everyone else. This is because the math you do inside your function dictates it. The addition of 0.5 at the end of the return statement controls this offset. The first and last contestants essentially are 'sharing' 1 contestant's wins. If that 0.5 is set to something like 0.75 or 0.25, contestant 1 and 2's wins will fluctuate accordingly.

To fix this, I was browsing the C++ library reference on the rand() function (http://www.cplusplus.com/reference/clibrary/cstdlib/rand/) and came up with what I feel is a little better random number generator.

Here is the same situation again, only with my random number generator instead of yours:

Code: Select all
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <string>

using namespace std;

// This is something more along the lines of what was in the reference.
int GetRand(int rangeMin, int rangeMax) {
    int realMax = rangeMax + 1;
    int diff = realMax - rangeMin;
    return (int)(rand() % diff + rangeMin);
}

int main() {
      srand((long)time(0));
      string names[10] = {"John","Brad","Jose","Nick","Tom","Chris","Zach","Matt","George","Steve"};
      int wins[10] = {0,0,0,0,0,0,0,0,0,0};
      int i = 0;
      int winner;
      do {
            winner = GetRand(0,9); //using my GetRand() function to pick a winner instead
            wins[winner]++;
            i++;
      } while (i < 10000);
      i = 0;
      do {
            cout << names[i] << " won " << wins[i] << " times." << endl;
            i++;
      } while (i < 10);
      return 0;
}


This produces a much more expected set of results, as follows:

John won 1006 times.
Brad won 951 times.
Jose won 977 times.
Nick won 1027 times.
Tom won 1014 times.
Chris won 1020 times.
Zach won 1003 times.
Matt won 1038 times.
George won 945 times.
Steve won 1019 times.

Please don't take this as me trying to be a smart @$$ or anything, and it's very possible that I could just be missing something... but I figured I'd at least let you know so you could take a look at it.

Thank you once again for all the hard work you've put in!

cheers,
Johnny
yellowaeroplane
 
Posts: 3
Joined: Mon Jun 15, 2009 8:58 pm

Next

Return to Snippets

Who is online

Users browsing this forum: No registered users and 0 guests