Name

Random Function

Syntax

function Random: Extended;
function Random(Limit: Integer): Integer;

Description

The Random function returns a pseudorandom number. Without arguments, it returns a floating-point number in the range ≤ Result < 1. The second form takes an integer argument and returns an integer in the range ≤ Result < Limit. Random is not a real function.

Tips and Tricks

  • Delphi uses a pseudorandom number generator (PRNG) with a cycle of 232. Although adequate for simple simulations, it is not suitable for use in encryption or other areas where you need a high-quality PRNG.

  • Call Randomize once to start the sequence of pseudorandom numbers at a different number each time you run the program.

Example

type
  TDieRoll = 1..6;
  TDiceRoll = 2..12;

// Simulate a roll of one ordinary die. Note that Random
// returns a value in the range [0, 5], so add 1 to get [1, 6].
function Die: TDieRoll;
begin
  Result := Random(6) + 1;
end;

// Simulate the roll of two ordinary dice.
function Dice: TDiceRoll;
begin
  Result := Die + Die;
end;

See Also

Randomize Procedure, RandSeed Variable

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.