Page 1 of 1

C Random Number Generator Rate Topic: -----

#1 stackoverflow  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 165
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Posted 11 July 2011 - 09:21 AM

C Random Number Generation


Disclaimer:

First and foremost I am aware there is an alternative tutorial similar to this one. The tutorial is called, "Producing Random Numbers" by Jessehk. I understand the tutorial is useful and I am thankful they contributed to Dream in Code. However, I find the tutorial to be a little lacking (no disrespect intended). I hope this tutorial can add more to the topic and give users more information. I was unable to find more tutorials concerning random numbers. I hope this tutorial will be useful!

What's an RNG?

An RNG is a Random Number Generator. Essentially, the job of an RNG is to produce a random number. It is worth noting "random" is actually pseudo-random. True random does not exist, but we can make pretty nifty RNGs. In order to produce a seemingly random number we need to 'seed' the RNG.

A seed is value which initializes the RNG. If you don't have a unique seed then the "random" sequence will always be the same! This tutorial will use a common method to maintain a unique random sequence every time the program is ran. However, there are better methods. Those methods are more advanced and in general most programmers don't need such random numbers. If you are doing encryption or other sensitive coding you may need a better seed.

What is an RNG used for?

Random numbers are used all over the place. A common use of random numbers is within games. For example-- you may want to spawn a random number of enemies or produce loot at a random rate. In those cases you are going to need a random number. Another common use is in encryption, but that is rather advanced. My favorite use of random numbers is within algorithms. If you look closely you can find random numbers everywhere and learning how to generate them is useful. To learn more about RNGs give this a read.

What do we need?

For this tutorial I am going to use C's functions. In particular we will be using these functions:

srand()
rand()
time()

Finally, we will make use of the modulus operator. In C modulus is done by using the % operator. In order to use the functions we will need to include the proper header files.

The functions srand and rand are located in the stdlib.h header file. The time function is located in the time.h standard header file. In short, our includes will look like such:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


The stdio.h library will be used for printf. We will want to print out some random numbers and make sure our functions are working.

Wait... modulus?

I will take a moment to explain how to use the mod operator. The mod operation is sometimes called the remainder operation. In essence, mod is a lot like doing plain old division but we only care about the remainder left over after the division.

For example, if I asked you what 10 divided by 5 was you would easily answer, "2" because 5 goes into 10 two times. If I asked you what 10 mod 5 was, you need to do the division and look at what is left over. Because 5 goes into 10 two times there is nothing left over and therefore the result of 10 mod 5 is 0. Now let's look at another example where there is a remainder.

If we look at 10 divided by 3... in plain old division we would think 3 goes into 10 three different times but there is a remainder. If we look at 10 mod 3 we can easily tell what the result of this is. We know 3 goes into 10 three times and 1 is remaining. Therefore, 10 mod 3 is 1.

Why do we care? We will use mod to limit our output. A number can be huge.. infinite! In order to make our number stay bound within a range we need to use mod.

Getting started

The rand() function returns a random number. The range of possible values is large and depends on your system and what it can handle.

Let's make a function which returns a random number.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int getRandomNumber(void)
{
  return rand();
}

int main(void)
{
  printf("%d\n", getRandomNumber());
  return 0;
}


When getting the output of this I got 1804289383. If you re-run you will notice you are getting the same random values. That feels pretty silly doesn't it? This is because we didn't seed rand(). Let's take a moment to seed it.

We will use srand and a unique seed. Where do we use srand? Well, we need to use it in a function that isn't where we plan to call rand. In this case we can use the main function because our self-made functions will be where we call rand.

What about our seed? Well, the most common technique is to use the current time in seconds. This is useful because time is always changing and gives us a unique output each time we run the program. We will seed via this, "srand(time(NULL));" without quotes. The NULL doesn't allow time to save the output in memory which is a plus-- because of security concerns. That isn't a concern to us now.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int getRandomNumber(void)
{
  return rand();
}

int main(void)
{
  srand(time(NULL));
  printf("%d\n", getRandomNumber());
  return 0;
}


Now we have a nice seed and a function which returns a random number. We are doing good but the range of random numbers is huge. Let's make a function which takes 2 arguments-- the base and the limit. We want to get a random number between the base and the limit (including the base and the limit). This is where mod is going to be useful.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int getRandomNumber(void)
{
  return rand();
}

int getRandomNumberRanged(int base, int limit)
{
  return rand() % (limit - base + 1) + base;
}

int main(void)
{
  srand(time(NULL));
  printf("%d\n", getRandomNumberRanged(0, 10));
  return 0;
}


There we go-- we have a useful function for producing a random number within a given range. If you don't understand the mod involved and the use of a limit and a base try to work it out on a sheet of paper.

So what can we do with this?

Well-- I figure now you may be pondering that question. I have put together a real simple program to display a random number being used. In this case we use a random value to represent the sides of a coin. We can then use this program to randomly flip a coin and tell us where it lands.

In addition to putting together this small program I have cleaned up the code and added comments. Also be warned I changed the name of the ranged function and removed the old version.

/**
* @title:  Heads or Tails
* @author: Stackoverflow
*
* @description: Simulates a coin toss
*
**/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define HEADS 1
#define TAILS 0

/**
* getRandomNumber - returns a random number within a bounded range
* @base: the lowest possible number
* @limit: the highest possible number
* @return: an integer within the bounded range is returned
**/
int getRandomNumber(int base, int limit);

int main(void)
{
  srand(time(NULL));

  if (getRandomNumber(0, 1) == HEADS){
    printf("Heads!\n");
  } else {
    printf("Tails!\n");
  }

  return 0;
}

int getRandomNumber(int base, int limit)
{
  return rand() % (limit - base + 1) + base;
}



Conclusion

I enjoyed writing this and I hope it helps people. Random numbers can be a lot of fun and they are not as complicated as they seem.

Exercise

A good exercise for using an RNG is to make a guessing game. The most common game is the guess-a-number game. The user must guess the number and if they are wrong the game will give the user a couple more tries. If the user can't guess in a couple tries the program should notify the user they lost and tell the user the number which was generated. I believe this is a good exercise and I leave it up to you to do!

Is This A Good Question/Topic? 3
  • +

Replies To: C Random Number Generator

#2 stayscrisp  Icon User is offline

  • フカユ
  • member icon

Reputation: 1009
  • View blog
  • Posts: 4,209
  • Joined: 14-February 08

Posted 12 July 2011 - 03:04 AM

Nice!
Was This Post Helpful? 0
  • +
  • -

#3 tarmizi_adam2005  Icon User is offline

  • جوروترا

Reputation: 243
  • View blog
  • Posts: 883
  • Joined: 18-April 09

Posted 12 July 2011 - 05:22 PM

Nice article ! helped me refresh my rusty C skills...
Was This Post Helpful? 0
  • +
  • -

#4 gojabe  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 25-November 09

Posted 13 July 2011 - 09:16 AM

But you have only used the library functions given previously by c, and used any method of your own to generate a psuedo random number.I mean a funtion of your own generating the random number by itself from scracth,and storing the seed somewhere i.e in *.txt file.
Was This Post Helpful? 0
  • +
  • -

#5 stackoverflow  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 165
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Posted 13 July 2011 - 10:21 AM

View Postgojabe, on 13 July 2011 - 04:16 PM, said:

But you have only used the library functions given previously by c, and used any method of your own to generate a psuedo random number.I mean a funtion of your own generating the random number by itself from scracth,and storing the seed somewhere i.e in *.txt file.


Hmm? Can you explain in more detail?

I have used library functions. I didn't intend to re-invent the wheel. Furthermore, pseudo-random numbers and seeds can be as simple as this or so incredibly complex even the greatest mathematicians are stumped.

I think using files is out of scope because file handling is something a little more challenging than random numbers. Most beginners will learn random numbers before they learn about file handling. Furthermore, storing a seed in a file, or even in memory can be incredibly dangerous if security is important.

I wrote this for beginners and I think a majority of beginners can use this for anything they want to do with random numbers.

If you have questions or want to know more then please ask.
Was This Post Helpful? 0
  • +
  • -

#6 gojabe  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 25-November 09

Posted 13 July 2011 - 11:21 PM

Or you could do it the traditional way.Take a number.Square it.Divide it by 2.Then mod it by the limit,to get it within the limit.Then when the function is called display the result,and also save it in a file.Next time when the function is called use the saved number for the computation.So there remains no sequence.Because the function can be called again after the machine is turned off.
Was This Post Helpful? 0
  • +
  • -

#7 stackoverflow  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 165
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Posted 14 July 2011 - 12:35 AM

I agree it can work but why would you prefer that method over seeding with a built in function?
Was This Post Helpful? 0
  • +
  • -

#8 gojabe  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 42
  • Joined: 25-November 09

Posted 14 July 2011 - 02:33 AM

Ya i understand your objective,but here the number after calling the function,the seed changes.Here i am computing on the seed itself.And after each function call a new number replaces the old number in the file.
Was This Post Helpful? 0
  • +
  • -

#9 Linkark  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 02-November 11

Posted 04 November 2011 - 09:51 AM

Thanks for the guide. It really helped me.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1