Are you practicing with programming languages and would like to understand how to generate random numbers using them? Do you want to draw participants for a school project using the computer but you don’t have the time/desire to install programs on the computer? If this is exactly the case, I think I have some solutions that are just right for you.
In this guide, in fact, I will explain how to generate random numbers using some of the most famous and used programming languages in existence. Furthermore, I will show you how to obtain the same result using a series of websites and apps for smartphones and tablets: in these last two cases, no computer knowledge is required.
Before going any further, however, I feel it is necessary to clarify an important point of the matter: in reality, the numbers generated by computers, smartphones and tablets are, in most cases, to be defined as pseudo-random . The reason is easy to explain: they are created starting from precise external conditions (e.g. the current date and time, the state of the CPU, disk, screen, the number of installed programs, the state of the Web server and so on) which, albeit in an extremely remote manner, can be artificially “reproduced” to always obtain the same figure. Having made this necessary clarification, I have nothing left to do but wish you happy reading and have fun!
How to generate random numbers in C++
Although C++ is an object-oriented language, the simplest and most effective way to generate a random number is to use the function rand(); included in the standard C++ library ( cstdlib), which allows you to pseudo-randomly generate a numeric value, basically between the value 0 and the value of the constant RAND_MAX – equal to at least 32767.
To ensure that the pseudorandom value is modified at each instance of program execution, you must use the function srand(), which is also present in the standard C++ library; in fact, this function allows you to set up the execution environment for the random generation of the digit, starting from the seed provided as an input value.
To optimize the result and exclude as much as possible the generation of identical results in multiple consecutive instances, it is possible to feed the function the timestampsrand of the current date and time; this latter value can be obtained through the function , included in the library . In other words, to generate a random number between 0 and RAND_MAX, you can use the following code.time()ctime
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std
int main(){
srand(time(NULL));
cout << "Numero casuale: " << rand();
return 0;}
If you wish, you can define the numeric range to which the random value belongs, using the modulo or % operator : the latter, if you have never used it before, returns the remainder of the division by the chosen value. To give you an example, the operation 6%4would return the value 2 (6 divided by four is one, with the remainder of two ).
So, to give a maximum limit to the pseudorandom number, it is sufficient to obtain the remainder of the division of the number by the value of the limit itself, increased by one; to impose, instead, both a maximum limit and a minimum limit, you must obtain the remainder of the division of the random number by the difference of the two limit values, increased by one, then adding the minimum value itself. If you want to integrate the above calculations into your C++ code, you can define the following functions.
int casuale_limMax(int max){ //genera numero casuale con limite massimo
srand(time(NULL));
return rand()%max;}
int casuale_doppioLim(int min, int max){ //genera numero casuale con limiti massimo e minimo
srand(time(NULL));
return rand()%(max-min+1)+min;}
Below is an example of source code ready to compile, with its main function.
#include <ctime>
#include <iostream>
#include <cstdlib>
using namespace std;
int casuale_doppioLim(int, int);
int main(void){
int m1, m2;
cout << "Inserisci il valore minimo: ";
cin >> m1;
cout << "Inserisci il valore massimo: ";
cin >> m2;
cout << "Il numero casuale generato è: "<< casuale_doppioLim(m1,m2) <<"\n";
return 0;
}
int casuale_doppioLim(int min, int max){
srand(time(NULL));
return rand()%(max-min+1)+min;}
How to generate random numbers in excel
If you need to insert random numbers into one or more Excel cells and do so without pretensions, you can use the function CASUALE(): in fact, the latter allows you to generate pseudo-random numbers between 0 and 1 (excluded). It goes without saying that, by multiplying the value obtained by the maximum required value plus one, you can manipulate the result as you see fit.
To give you an example, if you want to obtain a pseudo-random value between 0 and 100, locate the cell you are interested in and type the formula =CASUALE()*101 inside it , if you are reading this guide to understand how to generate random numbers on Excel with decimals , or =INT(CASUALE()*101), if you are interested in whole numbers only.
Even more convenient is the function CASUALE.TRA(minore;maggiore), which allows you to obtain random numbers between a minimum and a maximum value; both parameters can be positive or negative. For example, by inserting the formula into the cell of your interest =CASUALE.TRA(10;50), you will obtain an integer between the values 10 and 50.
The cell containing the random number will be automatically updated when the worksheet is recalculated, or when a formula or data is entered in a different cell. To perform manual recalculation, instead, press the F9 key on the keyboard (all cells containing randomly generated values will be recalculated).
How do you say? Do you need to know how to generate non-repeating random numbers Excel ? You can do this too. In fact, there is a particular function, called RANDBIT , which with the appropriate parameters allows you to extract a random value, both integer and decimal, from a matrix.
If combined correctly with the UNIQUE and INDEX functions , you can obtain a sequence of unique values, automatically inserted into the chosen column. Without going into complex definitions, the complete function we are talking about is the following.
=INDICE(UNICI(MATR.CASUALE(valori_in_memoria;1;num_iniziale;num_finale;SE_INTERO)); SEQUENZA(num_valori))
For example, if you want to create 250 pseudorandom values in memory, between 10 and 300, and insert 40 of them into the chosen column, you would write a formula very similar to the following one, inside the cell you want to use to contain the first value.
=INDICE(UNICI(MATR.CASUALE(250;1;10;300;VERO)); SEQUENZA(40))
If you want to obtain decimal numbers instead, you simply have to replace the word FALSE with the word TRUE, obtaining something similar to the following formula.
=INDICE(UNICI(MATR.CASUALE(250;1;10;300;FALSO)); SEQUENZA(40))
Note : The formulas and functions seen in this chapter are valid for Excel desktop, Excel online, and also for Excel on smartphones and tablets.
How to generate random numbers on Flowgorithm
Are you new to programming with Flowgorithm and would like to know how to generate a random number? Well, this function Random(X)is just what you need. In fact, it allows you to generate a random value between 0 and the number passed as a parameter. The latter, however, is not included in the count: as usual, if you want to generate a random number between 0 and 50, you will have to provide the value 51 as a parameter for the Random function, i.e. the number that acts as the maximum limit, increased by one unit.
Depending on your needs, you can insert the value returned by Random()(which is of integer type) either in a variable, to be managed as you see fit, or in a writing block; in the latter case, if you intend to insert the value in a text string delimited by quotation marks ( " "), remember to use the concatenation operator &, before calling the function itself
How to generate random numbers in C
If you need to generate random numbers in C language , you should know that you can use the same functions rand(), srand()and time() already mentioned for C++ : they are, in fact, shared by both languages. The only difference, in this case, is the name of the libraries they are part of, which are stdlib.h(the standard C library) and time.h(the library containing the predefined functions for managing timestamps).
Below, as an example, I leave you a working code that allows you to obtain random numbers between a minimum and a maximum value.
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int numCasuale(int, int);
int main(void){
int m1, m2;
printf("Inserisci il valore minimo: ");
scanf("%d", &m1);
printf("Inserisci il valore massimo: ");
scanf("%d", &m2);
printf("Il numero casuale generato è: %d", numCasuale(m1, m2));
return 0;
}
int numCasuale(int min, int max){
srand(time(NULL));
return rand() % (max-min+1)+min;
}
How to generate random numbers in Java
Among the characteristics of the Java programming language is certainly the quantity of predefined classes and objects , which allow you to manipulate practically any type of data.
For example, if we talk about random numbers, the java.util.Random class can certainly be useful : Random type objects, in fact, are responsible for instantiating pseudo-random values; each object can then be managed through the various methods defined for the object, in an extremely simple way.
To give you an example, the method nextInt()returns a pseudorandom integer value generated by the Random object; similarly, the method nextFloat()returns a decimal value. If you use Random objects, you do not need to define parameters or values to use as a seed , as everything is handled automatically at runtime.
Here’s an example of how Random objects work: the following portion of the method allows you to get a pseudorandom integer, either positive or negative.
import java.util.Random;
// altro codice dichiarativo
Random ra = new Random();
int numCas = ra.nextInt();
If, instead, you want to generate a random positive integer between a minimum and maximum value, you can pass the latter as arguments to the or methods nextInt(), nextFloat()taking care to add one unit to the maximum value. The code, then, would become as follows.
import java.util.Random;
// altro codice dichiarativo
Random ra = new Random();
int min=20;int max=50;
int numCas = ra.nextInt(min,max+1);
If you prefer, instead, to work on raw values , you can use the method , included in the Mathrand() class : it returns a decimal value, greater than or equal to zero and less than one, and must be manipulated using the same criteria already seen for C++ and C . Remember, if you want to use it, to perform an explicit cast to the type of primitive value to obtain.
If you need, for example, to obtain a pseudorandom integer between 50 and 250, you would use the following code.
int numCas=(int)(Math.random()*(251-50)+50);
How to generate random numbers in Python
Python , as you certainly know, is one of the syntactically simplest languages to assimilate: despite the almost limitless scenarios of use, you only need to know a few classes, with their associated modules and functions, to be able to obtain fully functional programs.
As regards the management of random numbers, for example, you can use the module random, included in the default library random.py : based on the functioning of the class of the same name, this module provides the user with a series of extremely useful functions, which allow you to generate and manipulate random numbers.
First, you need to initialize the pseudorandom number generator, using the function random.seed(seme): if no arguments are provided, such as seed, the timestamp provided by the system clock is used. This step is not mandatory, but it is recommended to obtain a series of values that can get closer to the definition of random.
That said, to generate a random integer between two values, just use the function random.randrange(minimo,massimo); to generate a decimal number, you can use the function random.uniform(minimo,massimo). Using the function random.random(), instead, you get a decimal value between zero (inclusive) and 1 (exclusive). Below is an example of working code.
import random
random.seed()
print("\n \n Numero casuale intero compreso tra 10 e 100: " , random.randrange(0,100))
print("\n \n Numero casuale decimale compreso tra 10.0 e 100.0: " , random.uniform(10,100))
Other systems for generating random numbers
Do you urgently need to get one or more random numbers without going through any programming language? Don’t worry, I think I have just what you need. For example, if you don’t want to install applications or programs to generate random numbers, know that there are some Web services that allow you to obtain more than sufficient results.
For example, by searching on Google phrases like random number or random number from [minimum value] to [maximum value] , you can ask the search engine to perform the operation on your behalf, even; if, instead, you want something more specific, you can refer to Random.org , a very famous website that promises to generate random numbers based on the so-called “atmospheric noise”, therefore not attributable to any pre-established mathematical algorithm.
To use it, connect to its home page , find the True Random Number Generator box (on the right) and, using the Min and Max fields , indicate the digits between which your random number must be included (e.g. between 0 and 50). When you’re done, press the Generate button and that’s it: the number you’re interested in will be shown, within a few moments, under the Result heading .
Again, if you want a system that allows you to generate random numbers even in the absence of Internet, you can refer to third-party applications useful for this purpose, such as Random Number for Android (also try to see if there is one on the alternative market on board your device , if the latter does not have Google services) or Random Generator for iPhone and iPad .
Although the applications in this category have very different interfaces, they almost always work the same way: you have to install them on your device following the classic procedure provided by the operating system , run them and choose to generate a random number . Once this is done, you just need to indicate the initial and final value to impose on the result (if necessary) and press the appropriate button to create the number . That’s all!

