Random numbers are useful for a wide variety of situations, such as generating data encryption keys, simulating and modeling complex phenomena, and for selecting random samples from larger data sets.

Random numbers have also been used aesthetically, for example in literature and music and for games and betting.

However, it is common for computer users not to correctly understand the “random number generator” of their system and the “random numbers” it produces, since it actually works with *pseudo-randomness*.

## concepts

Let's work a little on the conceptual basis about sequence and random numbers – random, and pseudo-randomness.

With the advent of computers, programmers recognized the need for a way to introduce randomness into a computer program. However, as surprising as it may seem, it is difficult to make a computer do something by accident. A computer follows your instructions blindly and is therefore completely predictable. (A computer that does not follow its instructions in this way is damaged.) There are two main approaches to generating random numbers using a computer: Pseudo-Random Number Generators (PRNGs) and True Random Number Generators (TRNGs). The approaches have quite different characteristics and each has its pros and cons.

Numbers calculated by a computer through a deterministic process cannot, by definition, be random.

Given knowledge of the algorithm used to create the numbers and their internal state, you can predict all numbers returned by subsequent calls to the algorithm, whereas with genuinely random numbers, knowledge of a number or an arbitrarily long sequence of numbers is useless anyway. anyway in predicting the next number to be generated.

Computer-generated “random” numbers are more appropriately called random numbers. *pseudo-random* and pseudo-random sequences of such numbers.

A variety of clever algorithms have been developed to generate sequences of numbers that pass all the statistical tests used to distinguish random sequences from those that contain some pattern or internal order.

### random number

In mathematics and statistics, a random number is pseudo-random or a number generated for, or part of, a set that exhibits statistical randomness.

When discussing unique numbers, a random number is one that is taken from a set of possible values, each of which is equally likely, i.e. a uniform distribution.

In common understanding, all numbers have an equal chance of being defined; on the other hand, neither has an advantage.

The definition of random sequence goes deeper and clarifies:

### random sequence

When discussing a sequence of random numbers, each number drawn must be statistically independent of the others.

The concept of random sequence is essential in probability theory and statistics. For statistics, a **random number** is a number that belongs to a numerical series and *cannot be predicted* from the previous members of the series. The concept of random number is a concept related to the numerical series to which the number belongs. A number can be random in one number series and not random in another.

In theoretical concepts, the theory of *axiomatic probability* deliberately avoids defining a random sequence. The theory of *traditional probability* does not state whether a specific sequence is random, but generally goes on to discuss the properties of random variables and stochastic sequences assuming some definition of randomness.

### Generation of sequences and random numbers

Random number generation is a process that generates a sequence of numbers or symbols that cannot reasonably be predicted better than by a random chance.

They can be generated by truly random hardware random number generators (HRNGS), which generate random numbers as a function of the current value of some attribute of the physical environment that is constantly changing in a way that is virtually impossible to model, or number generators pseudorandom (PRNGS), which generate numbers that appear random but are actually deterministic and can be reproduced if the state of the PRNG is known.

Various applications of randomness have led to the development of a number of different methods for generating random dice, some of which have existed since ancient times, among whose ranks are known “classic” examples, including dice rolling, coin tossing, shuffling cards, playing, the use of mille-leaf stalks (for divination) in the I Ching, and countless other techniques.

Due to the mechanical nature of these techniques, generating large amounts of sufficiently random numbers (important in statistics) required a lot of work and time. Thus, the results were sometimes collected and distributed as tables of random numbers.

There are several computational methods for generating pseudo-random numbers. All fall short of the goal of true randomness, although they can meet, with varying success, some of the statistical tests of randomness designed to measure how unpredictable their results are (that is, the degree to which their patterns are discernible).

This often makes them unusable for applications like encryption. However, carefully designed and cryptographically secure pseudo-random number generators (CSPRNGS) also exist, with special features designed specifically for use in cryptography.

### Pseudo-random number generators (PRNGs)

As the word 'pseudo' suggests, pseudorandom numbers aren't quite random in the way you might expect, at least not in the way you might be used to playing dice or lottery tickets.

Essentially, PRNGs are algorithms that use mathematical formulas or simply pre-calculated tables to produce sequences of numbers that appear random. A good example of PRNG is the linear congruent method.

Much research and investment has gone into the theory of pseudo-random numbers, and the modern algorithms for generating them are so good that the numbers actually look like they are truly random.

The basic difference between PRNGs and TRNGs is easy to understand when comparing computer-generated random numbers to the results of tossing a die.

Considering that PRNGs generate random numbers using mathematical formulas or pre-calculated lists, an equivalent method would be for someone to roll a die many times and record the results. Whenever you then rolled the dice, you would get the next result on the list. The results appear random, but are actually predetermined.

TRNGs, on the other hand, work by making a computer actually *roll the dice* or, more commonly, use some physical phenomenon that is easier to connect to a computer than data.

PRNGs are efficient, that is, they can generate many numbers in a short amount of time, and deterministic, which means that a given sequence of numbers can be reproduced at a later date if the starting point of the sequence is known (*seed* or seed).

Efficiency is a good feature if your application needs a very large amount of numbers, and determinism is useful if you need to reproduce the same sequence of numbers again at a future stage or context.

Normally, PRNGs are also periodic, that is, they are finite. This means that the sequence will end up repeating itself. While this is not always a desirable feature, modern PRNGs are so long-lived that they can be ignored for most practical application purposes.

For all these characteristics, PRNGs end up being suitable in applications where many numbers are needed and where it is useful that the same sequence can be reproduced easily.

Popular examples of such applications are simulation and modeling systems.

PRNGs, however, are not suitable for applications where numbers are required to be truly unpredictable, such as cryptographic systems, craps, or other games of chance.

It is important to understand that while good PRNG algorithms exist, they are not always used as it is easy to get unwanted surprises.

Here's an example of the popular web programming language PHP:

If you use PHP on GNU/Operating System distributionsLinux, you are likely to be satisfied with random numbers generated by the language.

However, if you use PHP for Microsoft Windows, you will likely find that your random numbers are not generated as expected, as shown in this 2008 visual analysis.

Another example is from the year 2002, when a researcher reported that PRNG on MacOS was not good enough to scientific simulation of virus infections.

I'm not claiming that these situations remain until today, especially considering the evolution of Operating Systems and programming languages. The main issue is that the result, even if a PRNG meets the needs of your application, should read evaluated carefully so as not to receive results that are out of the expected for your application.

### True Random Number Generators (TRNGs)

Compared to PRNGs, TRNGs guarantee randomness using physical phenomena and input it into a computer. You can think of this as a rolling dice connected to a computer.

However, normally, a physical phenomenon is used that is easier to connect to a computer than data :-D.

The physical phenomenon can be very simple, such as small variations in someone's mouse movements or the amount of time between keystrokes on a keyboard when typing.

In practice, however, you must be careful about the phenomenon and the source you choose. For example, it can be tricky to use keystrokes in this way, because keystrokes are often stored in *buffer* by the computer's operating system, which means that multiple keystrokes are collected before being sent to the program waiting for them. For a program that waits for keystrokes, it will appear that the keys were pressed almost simultaneously and there may not be much randomness in this process.

But there are many other ways to get true randomness on your computer.

A very good physical phenomenon to use is a radioactive source. The points in time when a radioactive source decays are completely unpredictable and can be easily detected and fed into a computer, bypassing any buffering mechanisms in the operating system.

Fourmilab's HotBits service in Switzerland is an excellent example of a random number generator that uses this technique.

Another suitable physical phenomenon is the *atmospheric noise*, very easy to pick up with a normal radio. This is the approach used by RANDOM.ORG.

You can also use background noise from an office or lab, but be aware of the standards. Your computer's fan can contribute to the background noise, but since the fan is a rotating device, it's likely that the noise it makes is not as random as atmospheric noise.

Undoubtedly, the most visually interesting approach is the washing generator, which was built by Silicon Graphics and used pictures of lava lamps to generate random numbers.

The project is no longer operational, but one of its inventors continues work, without the lava lamps, on the site. LavaRnd.

Yet another approach is the Java EntropyPool, which gathers random bits from a variety of sources, including HotBits and RANDOM.ORG, as well as from web page hits received by EntropyPool's own server.

Regardless of which physical phenomenon is used, the process of generating true random numbers involves identifying small, unpredictable changes in the data. For example, HotBits uses small variations in the delay between occurrences of radioactive decay, and RANDOM.ORG uses small variations in the amplitude of atmospheric noise.

As for the characteristics of TRNGs, they are quite different from PRNGs.

Firstly, TRNGs are generally inefficient compared to PRNGs, taking much longer to produce numbers. They are also non-deterministic, meaning that a given sequence of numbers cannot be reproduced, although the same sequence can, of course, occur multiple times by chance. Finally, TRNGs do not have periodization, it is possible to generate an infinite sequence of random numbers.

## Random number generation programs

The following is a list of programs, websites with internet services and libraries (programming packages) or material with strategies in programming languages for generating random or pseudo-random numbers.

The first part presents a program to test random sequences, followed by a list of software and internet services for generating random numbers, ending with tutorials and examples of how to generate random numbers in programming languages such as C, PHP, Python, Java, Javascript , among others.

Tests for random numbers

### Testing pseudo-random byte sequences

You can use the ENT program (*The Pseudorandom Number Sequence Test Program*) to apply tests to sequences of bytes and reports how random they appear to be.

When you run it on data generated by a high-quality pseudo-random sequence generator, you will find that it generates data that is indistinguishable from a sequence of randomly chosen bytes. Indistinguishable, but not genuinely random.

Software features and services for generating sequences and random numbers:

### random.org

RANDOM.ORG offers real random numbers to anyone on the Internet. The randomness comes from atmospheric noise, which for many purposes is better than the pseudo-random number algorithms commonly used in computer programs. People use RANDOM.ORG to run sweepstakes, lotteries and sweepstakes, to conduct online games, for scientific applications and for art and music. The service has been around since 1998 and was built by Dr. Mads Haahr of the School of Computer Science and Statistics at Trinity College, Dublin, Ireland. Today, RANDOM.ORG is operated by Randomness and Integrity Services Ltd.

**free services**

The site offers a variety of free services separated by categories:

##### Games and Lotteries

- O
*Quick Pick*lottery is perhaps the most popular on the Internet, with over 280 lotteries *Keno Quick Pick*for the popular game played in many countries*coin flipper*will give you heads or tails in many coins*Dice Roller*does exactly what it says: rolls dice- Playing
*Card Shuffler*will draw cards from several shuffled decks *Birdie Fund Generator*will create bird holes on golf courses

##### Numbers

- O
*integer generator*creates random numbers at configurable intervals - O
*Sequence Generator*will randomize an entire sequence of your choice *integer set generator*make sets of non-repeating integers- O
*Gaussian Generator*creates random numbers to fit a normal distribution - O
*Decimal Fraction Generator*creates numbers in the range [0,1] with configurable decimal places *raw random bytes*are useful for many cryptographic purposes

##### Lists, strings and maps

*List Randomizer*will randomize a list of everything you have (names, phone numbers, etc.)*String Generator*create random alphanumeric strings- O
*password generator*creates secure passwords for your Wi-Fi or extra Gmail account *Clock Time Generator*will choose random times of day- O
*Calendar Date Generator*will pick random days over nearly three and a half millennia - O
*Geographic Coordinates Generator*will choose a random location on the surface of our planet *bitmaps*in black and white- O
*Hexadecimal color code generator*will choose color codes eg to use as web colors *pre-generated files*contain large amounts of random bits for download*Pure White Audio Noise*for compositing or just testing your audio equipment*jazz scales*to practice improvisation for jazz guitar students- THE
*short prose*randomly generated by Samuel Beckett *randomizer**DNA protein sequence*(on Bio-Web)

RANDOM.ORG also has widgets for websites and an API for developing applications that need to generate truly random numbers like games.

### hotbits

hotbits is an Internet resource that brings genuine random numbers, generated by a process fundamentally governed by the uncertainty inherent in the quantum mechanical laws of nature, directly to your computer in a variety of ways.

HotBits are generated by synchronizing successive pairs of radioactive decays detected by a Geiger-Müller tube connected to a computer.

You request your share of HotBits by filling out a request form specifying how many random bytes you want and in what format you want them delivered. Your request is relayed to the HotBits server, which sends the random bytes back to you over the web.

Because the HotBit-generating hardware produces data at a modest rate (about 100 bytes per second), requests are filled from an “inventory” of pre-built HotBits.

Once the random bytes are delivered to you, they are immediately discarded – the same data will never be sent to any other user and no record is kept of the data on this or any other website – *Of course, if you're using the random data for encryption or other security-related applications, you can't be sure the service isn't keeping a copy. They claim they don't*.

An alternative to downloading HotBits for later use is provided by randomX package for Java. A program developed with randomX can select from a variety of pseudo-random sequence generators or genuine random HotBits data, obtained on demand from the Internet.

List of tutorials for programming random number generation

### C language tutorial

Tutorial for generating random (random) numbers in C is an article that demonstrates how to generate random numbers using the C language and the function `rand`

. This article can be used as a basis for generation also in C++.

**keep up to date**

Don't forget to follow me on twitter and sign the Mazer.dev channel on Youtube to receive updates on new articles, video lessons and free courses in software development and engineering.

Pingback: Tutorial for generating random (random) numbers in C