Random Number Generators

Random Number Generator: How Do Computers Generate Random Numbers?

People have been playing random numbersfor millennia. Hence, this idea isn't a new one. From the lottery that was played in ancient Babylon as well as roulette machines in Monte Carlo, to dice games in Vegas The idea is leaving the end outcome to chance.

But gambling aside, randomnesshas numerous uses in science, statistics, cryptographyand further. However, using dice, coins or other similar devices as a random device comes with limitations.

Because of the mechanical nature of these techniques, generatinglarge quantities of random numbers can take a quantity of effort and time. Thanks to human ingenuity, we are able to use more effective techniques and tools available to us.

Methods of generating random numbers

True Random Numbers

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

Let's examine two major methods for generating random numbers. The first methodis the HTML1 method. It isbased on physical processes, and harvests the source of randomness from some phenomena that's supposed to be random.

Such a process takes place beyond the computer. It is measured and adjusted to take into account possible distortions caused by an assessment process. Examples include radioactive decay, the photoelectric effect, cosmic background radiation, atmospheric noise (which we will use to illustrate this story), and other sources.

So, random numbers created using this type of randomness are considered to be " true" random numbers.

Technicallyspeaking, the hardware is comprised of a device that converts energy to another (for example, radiation is converted into an electrical signal) along with an amplifier as well as an analog-to-digital converter that can convert the output into a digital number.

What are Pseudorandom Numbers?

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

In addition as an alternative to "true" random numbers, the second approach in generating random numbers involves computational algorithms that could produce seemingly random results.

Why does it seem so random? Because the final outcomes are in fact completely controlled by an initial value which is also known as"the "seed" value or key. So, if you knew the value of the key and how the algorithm functions you could replicate these almost random results.

Random number generators like this are often referred to as Pseudorandom numbers generators. They, as they produce Pseudorandom numbers.

Although this kind of generator isn't able to collect any data from sources of naturally occurring randomness, gathering keys is feasible when required.

Let's compare some aspects of real random number generators, also known as TRNGs and pseudorandom number generators , also known as PRNGs.

PRNGs are quicker than TRNGs. Because they are deterministic they are a great choice when you want to replay the sequence of events. This helps a great deal in testing your code, for example.

On the other hand TRNGs aren't regular and work better in areas that require security, such as encryption.

An length is the number of iterations a PRNG go through before it starts repeating itself. Therefore, all other things being equal, a PRNG running longer timeframe will need more computer resources to predict and even crack.

Example Algorithm for Pseudo-Random Number Generator

The computer's execution is founded on a set guidelines to be followed. For PRNGs in general, those rules revolve around the following:

  1. Accept some initial input number, which is a seed or key.
  2. Apply the seed to a series of mathematical operations in order to get the result. This result is the random number.
  3. Use the resultant random number to determine the next repeat.
  4. Continue the procedure to recreate randomness.

Let's take a look at an example.

The Linear Congruential Generator

The generator creates a series of pseudorandom numbers. With an initial seed of X0 with integer parameters such as a as multipliers, B as the increment and m as the modulus the generator is defined by the linear relationship: Xn (aXn-1 + b)mod (m). or using a more programming-friendly terminology: X n = (a * X n-1 + b) percent M.

Each member has to fulfill the following conditions:

  • m > 0(the modulus is positive),
  • Zero a"m"(the multiplication factor is positive but smaller than the modulus),
  • 0.= the modulus b = m (the increment is not negative, but less than that of the modulus), and
  • 0.means X 0 < 1(the seed is not negative however it is less than the modulus).

Let's design a JavaScript function that will take the initial values as arguments and returns an array of random numbers that are of length a specified 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 Consgruential Generator one of the oldest and best-known PRNG algorithms.

As for random number generator algorithms that can be used by computers, they've been around to the 1950s and 1940s (the Middle-square method as well as the Lehmer generator for instance) and continue to be implemented today ( Xoroshiro128+, Squares RNG and many more).

A Sample Random Number Generator

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

I could've made use of JavaScript's Math.random()function to be the basis and generated output as pseudorandom numbers, like I have in earlier articles (see Multiplication Chart Code Your Own Time Table).

But this article itself is about generating random numbers. So I decided to learn how to gather "true" randomness based data and share my discovery with you.

So below can be described as the "true" Random Number Generator. Choose the parameters and then hit Generate.True Random Number GeneratorBinary Decimal Hexadecimal GenerateResult

The code is able to retrieve data from any API via Random.org. This resource online has many useful instruments that are flexible and customizable, and comes with a great documentation with it.

The randomness is due to atmospheric noise. I was able Asynchronous functions. That's a huge benefit for the future. The core function looks like 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 accepts permit the user to modify the output of random numbers. For instance, min and max allow users to define upper and lower limit on output generated. Also, base determines if output is printed as decimal, binary or hexadecimal.

In the end, I went with this particular configuration, but there are many other options available from the source.

When you click on the Generate button after which then the handleGenerate() function is called. It calls the getRandom() asynchronous function to handle error handling and outputs the result:

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

The remainder of the code is concerned specifically with HTML design, structure and styling.

The program is ready for embedding and use on this page. I broke it down into component parts and supplied it with full instructions. It can be easily modified. It is also possible to alter the functions and styles as your needs require.

Comments

Popular posts from this blog

What Is a Calorie?

Random Number Generators

Why are BMIs useful ?