Generating a random number in Delphi is a common task for simulations, games, and testing. Delphi provides a built-in Random function that returns a floating-point number between 0 and 1, and you can easily scale it to get integers within a range. This guide covers the essential steps, common pitfalls, and tips for working with randomness in Delphi (including both classic Delphi and Delphi for .NET where relevant).
What You’ll Need
- Delphi IDE (any recent version, e.g., Delphi 10.x, 11.x, or 12.x) with a VCL or FMX application project.
- Basic familiarity with the Delphi code editor and event handlers (like a button’s OnClick).
- No additional libraries are required; the Random function is part of the System unit, which is automatically available.
Step-by-Step
- Initialize the random number generator (optional but recommended). In your main form’s
OnCreateevent (or before the first call to Random), callRandomize. This seeds the generator with a value based on the system clock, ensuring different sequences each run. Without it, you get the same sequence every time. - Generate a floating-point random number between 0 and 1. Use the
Randomfunction with no arguments. Example:var r: Double; r := Random;This returns a value >= 0 and < 1. - Generate an integer within a specific range. Use
Random(Number)where Number is an integer. This returns a value from 0 to Number-1. For example,Random(10)gives 0..9. To get a range like 1..10, add 1:Random(10) + 1. - Generate a random integer between two arbitrary bounds (Min and Max). Use the formula:
Min + Random(Max - Min + 1). For instance, to get a number between 5 and 15 inclusive:5 + Random(11). - For a random floating-point number in a range (e.g., 2.5 to 7.5), use:
Min + Random * (Max - Min). Example:2.5 + Random * 5gives a value from 2.5 to 7.5 (not including 7.5). - If you need a random Boolean (True/False), use
Random(2) = 0orRandom < 0.5. - For a random element from an array, use the array’s length:
MyArray[Random(Length(MyArray))]. - To generate a random string (e.g., a random digit), combine Random with a character set:
Char(Ord('0') + Random(10))yields a digit. - Test your code. Place a button on a form, and in its OnClick event, write code to generate a number and display it in a label or message box. For example:
ShowMessage(IntToStr(Random(100)));
Common Mistakes
- Forgetting to call Randomize. This is the most frequent error. Without it, your program always produces the same sequence of numbers, which may be useful for debugging but not for real randomness.
- Misunderstanding the upper bound.
Random(N)returns 0 to N-1, not 1 to N. Many beginners expectRandom(10)to return 1 through 10, but it returns 0 through 9. - Using Random without an argument when you need an integer.
Randomreturns a Double; using it directly in an integer context may cause a compiler error or unexpected rounding. - Overflow with large ranges. If Max – Min + 1 exceeds the integer range, you’ll get an error. For large ranges, consider using Int64 or a different approach.
Tips
- Call Randomize once, typically in the main form’s OnCreate or in the project file before the main form is shown. Calling it repeatedly (e.g., before each random call) can actually reduce randomness because the seed may repeat if called in quick succession.
- For cryptographic randomness, use the
TCryptoRandomclass from the System.Net.Security unit (in Delphi 10.3+) or the Windows APICryptGenRandom. The built-in Random is not secure. - To generate a random number in a specific distribution (e.g., normal distribution), you’ll need to implement a transformation like the Box-Muller method, as the built-in Random is uniform.
- When debugging, temporarily remove Randomize to get a repeatable sequence. This helps reproduce bugs.
Troubleshooting
- You get the same number every time. This is almost always because you didn’t call
Randomize. Add it to your form’s OnCreate. - Compiler error: ‘Random’ is not a function. This happens if you have a variable or unit named Random that shadows the System.Random. Rename your variable or fully qualify as
System.Random. - Random number is always 0. If you use
Random(1), it always returns 0 because the range is 0..0. Use a larger argument. - Your code works but the numbers are not evenly distributed. This can happen if you use
Round(Random * N)instead ofRandom(N). Rounding introduces bias. UseRandom(N)for integers. - In a console application, Randomize seems to have no effect. Make sure you call it before any Random call, and that your program actually runs multiple times. If you run from the IDE, the seed may change each run anyway.
Frequently Asked Questions
- Q: How do I generate a random number between 1 and 100?
A: UseRandom(100) + 1. This gives 1 to 100. - Q: Why do I need to call Randomize?
A: Randomize seeds the generator with a time-based value. Without it, the sequence is the same every time your program runs, which is rarely what you want. - Q: Can I use Random in a multi-threaded application?
A: The built-in Random is not thread-safe. Use a separate random generator per thread, or use a lock. Consider usingSystem.Math.RandomRangeor a thread-safe implementation. - Q: How can I generate a random real number between 0 and 1 with more precision?
A: The default Random returns a Double with about 15 decimal digits of precision, which is sufficient for most purposes. If you need more, you can combine two Random calls, but that’s rarely necessary. - Q: Is there a way to generate a random number without using Randomize?
A: Yes, you can use a constant seed by not calling Randomize, but that gives the same sequence every run. If you want a different sequence each run, you must call Randomize. - Q: Does Delphi’s Random work the same in FMX and VCL?
A: Yes, the Random function is part of the System unit and works identically in both VCL and FMX applications.
Related
- Data Entry Qualification Online: What You Need
- How to Add Border Lines in Excel (Step-by-Step)
- How to Generate Random Numbers in Arduino
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Wrap Text in Google Sheets: A Quick TutorialTo wrap text in Google Sheets, select the cell or range, then choose Format > Wrapping > Wrap.…
- Excel Kata for Data Analysis: Practice With PurposeAn Excel kata for data analysis is a short, repeatable spreadsheet challenge that helps you practise a specific…
- Fit Columns to Text in Excel: Quick Methods and FixesTo fit a column to its text in Excel for Microsoft 365 on Windows, select the column and…
- Excel Track Changes: How to Turn It OnTo turn on the traditional Track Changes mode in Excel for Microsoft 365 on Windows, open the workbook,…
- Excel Freeze Panes: Why the Option Is UnavailableIf Excel will not let you freeze panes, first press Esc to exit cell-editing mode, then click a…
- Fixing a Corrupted Excel File: Recovery StepsTo fix a corrupted Excel file, first make a copy of it, then in Excel for Microsoft 365…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.