Programmer's Wiki

Random number

406pages on
this wiki
Add New Page
Talk1 Share

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 Edit

C Edit

int num = rand() % 10; // generates a number from 0 to 9

.NET Edit

The System.Random class is used to generate random numbers. Each instance is a separate pseudorandom number generator.

C# Edit

Random random = new Random();
random.Next(10); // generates a number from 0 to 9

Visual Basic Edit

Dim rand As New Random()

Java Edit

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 Edit

int(rand(10)) # generates a number from 0 to 9

PHP Edit

rand(0, 9) // generates a number from 0 to 9
mt_rand(0, 9) // like above, but use the MT method

PL/I Edit

dcl time builtin;    /* System time HHMISS999 */
dcl random builtin;

dcl number  bin fixed(15);

number = random(time()) * 100 + 1; /* Range 1 - 100 */

Python Edit

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 Edit

rand(10) # generates a number from 0 to 9

Ada Edit

   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;
   Num := Rand_Int.Random(seed);

See also Edit

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.