The ability to generate random numbers can be useful in certain kinds of programs, that need to model random events.In real life, we often generate random results by doing things like flipping a coin, rolling a dice, or shuffling a deck of cards. These events involve so many physical variables (eg. gravity, friction, air resistance, momentum, etc…) that they become almost impossible to predict or control, and produce results that are for all intents and purposes random.
A pseudo-random number generator (PRNG) is a program that takes a starting number (called a seed), and performs mathematical operations on it to transform it into some other number that appears to be unrelated to the seed. It then takes that generated number and performs the same mathematical operation on it to transform it into a new number that appears unrelated to the number it was generated from.
Code:
# #include <stdafx.h>
# #include <iostream>
# using namespace std;
#
# unsigned int PRNG()
# {
# // our initial starting seed is 2
# static unsigned int nSeed = 2;
#
# // Take the current seed and generate a new value from it
# // Due to our use of large constants and overflow, it would be
# // very hard for someone to predict what the next number is
# // going to be from the previous one.
# nSeed = (2 * nSeed + 50);
#
# // Take the seed and return a value between 0 and 200
# return nSeed % 200;
# }
#
# int main()
# {
# // Print 100 random numbers
# for (int nCount=0; nCount < 200; ++nCount)
# {
# cout << PRNG() << "\t";
#
# // If we've printed 5 numbers, start a new column
# if ((nCount+1) % 3 == 0)
# cout << endl;
# }
# }
Bookmarks