Generating random numbers is a task that comes up a lot while programming. It is often important to know how to do it properly as a lot of languages generate pseudorandom numbers by default.
"Real" random numbers are numbers that are generated with statistical randomness, in contrast to pseudorandom numbers which are generated by using a seed. Supplying the same seed to a pseudorandom number generator would yield the same numbers. In most programming languages, the seed is set to the system's time by default; this will create the illusion of generating statistically random numbers.
Examples[]
C[]
srand(time(0));
int num = rand() % 10; // generates a number from 0 to 9
.NET[]
The System.Random class is used to generate random numbers. Each instance is a separate pseudorandom number generator.
C#[]
Random random = new Random();
random.Next();
random.Next(10); // generates a number from 0 to 9
Visual Basic[]
Dim rand As New Random()
rand.Next(10)
Java[]
Random rand = new Random(System.currentTimeMillis()); //seeding Random with current time
// Random integers
int i = rand.nextInt();
int j = rand.nextInt(10); // generates a number from 0 to 9
See Also
Perl[]
int(rand(10)) # generates a number from 0 to 9
PHP[]
rand(0, 9) // generates a number from 0 to 9
mt_rand(0, 9) // like above, but use the MT method
PL/I[]
dcl time builtin; /* System time HHMISS999 */ dcl random builtin; dcl number bin fixed(15); number = random(time()) * 100 + 1; /* Range 1 - 100 */
Python[]
import random
print random.random()
print random.randrange(10) # generates a number from 0 to 9
print random.randint(0, 9) # generates a number from 0 to 9
Ruby[]
rand(10) # generates a number from 0 to 9
Ada[]
declare
type Rand_Range is range 0..9;
package Rand_Int is new Ada.Numerics.Discrete_Random(Rand_Range);
seed : Rand_Int.Generator;
Num : Rand_Range;
begin
Rand_Int.Reset(seed);
Num := Rand_Int.Random(seed);
Put_Line(Rand_Range'Image(Num));
end;
See lso[]
- Shuffling
- Mathematical functions
- C# Codes