Random Number Generators

Random Number Generator: How Do Computers Generate Random Numbers?

People have been using random numbersfor millennia. So the concept isn't new. From the lottery system in the ancient city of Babylon to roulette machines in Monte Carlo, to dice games in Vegas the aim will be to give the final outcome to chance.

However, aside from gambling, randomnesshas numerous uses for science, statistics cryptographyand many more. However, using dice, coins or other similar devices as a device for randomization has its limitations.

Due to their mechanical character of methods, generatinglarge quantities of random numbers demands a huge amount of time and effort. Human ingenuity is the reason why we have more efficient instruments and methods that are available.

Methods for generating random numbers

True Random Numbers

Image of an analog-input digital output processing device. Photo by Harrison Broadbent

We will look at two methods to generate random numbers. The first methodis the HTML1 method. It isbased on an actual physical process. The second method takes the randomness source from a phenomena that's supposed to occur randomly.

Such a process takes place in the absence of the computer. It is measured and adjusted to take into account possible errors due to measurements. Examples include photoelectric effect, cosmic background radiation, atmospheric noise (which we will use to illustrate this story) and many others.

Thus, random numbers generated in the context of such randomness can be believed to be " true" random numbers.

The hardware comprises a gadget that converts energy to another (for instance, radiation into electronic signals) along with an amplifier and an analog-to-digital converter to turn the output into a digital number.

What are Pseudorandom Numbers?

Picture of computer code flowing through computer screen. Photo by Markus Spiske.

As an alternative to "true" random numbers, the second way that is used for generating random numbers involves computational algorithms that produce a variety of random results.

How can this be so? Because the final outcomes are actually controlled by an initial value commonly referred to as"the seed value . It is also known as the key. Therefore, if you knew the key value and how the algorithm works you could duplicate the almost random results.

Random number generators of this kind are commonly referred to as Pseudorandom number generators. As consequently, generate Pseudorandom numbers.

Even though this kind of generator doesn't typically collect any data from natural randomness or randomness. However, the collection of keys is possible when needed.

Let's take a look at the similarities and differences between real random number generators, also known as TRNGs and pseudorandom number generators also known as PRNGs.

PRNGs are faster than TRNGs. Because they are deterministic, they are useful for replaying the sequence of events. This helps a great deal in testing your code, for instance.

However TRNGs do not have a regular schedule and are better suited for secure roles, like encryption.

It is said that a time is the number of iterations a PRNG goes through before it will begin repeating itself. All other things being equal, a PRNG running a longer period would take more computer resources to predict and crack.

Example Algorithm for Pseudo-Random Number Generator

A computer executes code which is built on a set of guidelines to be followed. In the case of PRNGs generally they are governed by the following:

  1. Accept some initial input number. It is a seed or key.
  2. Apply that seed in a sequence of mathematical operations to generate the result. This results in the random number.
  3. Use that random number as the basis for your next version.
  4. Repetition the process to mimic randomness.

Let's take a look at an illustration.

The Linear Congruential Generator

This generator produces a series of pseudorandom numbers. With an initial seed that is X0 and integer parameters such as with a being the multiplier and B as the increment and the modulus as m, it is defined as the linear relation: the formula Xn = (aXn-1 + b)mod mod. For a more programming-friendly formalism: X n = (a * X n-1 + b) % 1.

Each of the members has to fulfill the following conditions:

  • m > 0.(the modification is positive),
  • 0 , a,"m"(the multiplication factor is positive but less than the modulus),
  • 0 the modulus is b (the increment is not negative but is lower then the modulus), and
  • 0.<is the value of X 0 < the m(the seed isn't negative but is lower in comparison to the modulus).

Let's develop an JavaScript function that will take the arguments as the starting values to return an array of numbers of the given length:

  // x0=seed; a=multiplier; b=increment; m=modulus; n=desired array length; const linearRandomGenerator = (x0, a, b, m, n) =>  const results = [] for (let i = 0; i < n; i++)  x0 = (a * x0 + b) % m results.push(x0)  return results  

The Linear Congruential Generator (LCG) is one of the oldest and best-known PRNG algorithms.

For random number generator algorithms that are able to be executed by computers, they are in use as early as the 1950s and 1940s (the Middle-square method as well as the Lehmer generator for instance) and continue to be created today ( Xoroshiro128+, Squares RNG and many more).

A Sample Random Number Generator

When I chose to write this article on embedding a random number generator within the web page, I had a choice to make.

I could've used JavaScript's Math.random()function as the basis to generate output in pseudorandom numbers like I have done in previous articles (see Multiplication Chart code your own Time Table).

However, this article involves generating random numbers. So I decided to learn how to collect "true" randomness based data and share it with you.

Here is the "true" Random Number Generator. Make the settings and hit Generate.True Random Number GeneratorBinary Decimal Hexadecimal GenerateResult

The code retrieves data using One of these APIs through Random.org. This website has many useful, customizable tools and comes with an excellent guideline to go with it.

The randomness stems from atmospheric noise. I was able to utilize Asynchronous functions. This is a huge advantage for the future. The function at its core is this:

// Generates a random number within user indicated interval const getRandom = async (min, max, base) =>   const response = await  fetch("https://www.random.org/integers/?num=1&min="+min+"  &max="+max+"&col=1&base="+base+"&format=plain&rnd=new")  return response.text()   

The parameters it takes allow a user to customize the output of random numbers. For example, min and max allow users to set lower and upper levels for output. Furthermore, base decides if output is printed as binary, decimal or the hexadecimal.

In the end, I went with this configuration but there are many others available at the source.

After you click the Generate button after which you will see the handleGenerate() function is called. It , in turn, invokes the getRandom() asynchronous function, manages error handling, and outputs results:

// Output handling const handleGenerate = () => (

The rest of the code deals specifically with HTML style, layout and styling.

It is now ready to be used and embedded within this web page. I have broken it up into smaller parts and supplied it with explicit notes. It is easily customizable. You are able to modify the functions and styles as the requirements of your business require.

Comments

Popular posts from this blog

What Is a Calorie?

Random Number Generators

Why are BMIs useful ?