To generate random numbers in code, use a language’s built-in random function: in Python, random.randint(1, 100) returns a random integer between 1 and 100; in C, rand() % 100 + 1 does the same (after seeding with srand(time(0))); in Excel, =RANDBETWEEN(1, 100) generates a random integer in that range. These functions are pseudo-random, meaning they use an algorithm to produce numbers that appear random but are actually deterministic based on an initial seed value.
What Randomness Really Means in Computing
Computers are deterministic machines, so they cannot produce truly random numbers on their own. Instead, they use pseudo-random number generators (PRNGs) — algorithms that take a seed (a starting number) and apply mathematical operations to generate a sequence that mimics randomness. The sequence is repeatable if you use the same seed, which is useful for debugging or simulations. True randomness requires external entropy sources, like radioactive decay or atmospheric noise, or hardware random number generators that measure physical phenomena.
How Pseudo-Random Number Generators Work
PRNGs use a variety of algorithms. The most common is the linear congruential generator (LCG), which computes the next number as (a * current + c) % m, where a, c, and m are constants. For example, the C standard library’s rand() often uses an LCG, though the exact parameters vary by implementation. Modern languages like Python use the Mersenne Twister (MT19937), which has a much longer period (2^19937-1) and better statistical properties. For cryptographic purposes, you need a cryptographically secure PRNG (CSPRNG), such as random.SystemRandom in Python or /dev/urandom on Unix systems, which uses OS entropy.
Generating Random Numbers in Python
Python’s random module is the standard tool. To get a random integer, use random.randint(a, b) (inclusive). For a random float between 0 and 1, use random.random(). To pick a random element from a list, use random.choice(list). Here’s a simple example:
import random
print(random.randint(1, 6)) # Simulate a die roll
If you need reproducibility, set the seed with random.seed(42). For security-sensitive applications, use secrets module, e.g., secrets.randbelow(100).
Generating Random Numbers in C
In C, the stdlib.h library provides rand(), which returns an integer between 0 and RAND_MAX (typically 32767). To get a range, use the modulo operator, but be aware of modulo bias — if the range does not evenly divide RAND_MAX, some numbers will appear more often. A better method is to use rejection sampling. Always seed the generator with srand(time(0)) to get different sequences on each run. Example:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0));
int r = rand() % 6 + 1; // 1 to 6
printf("%d\n", r);
return 0;
}
For better randomness, use the C11 rand_s on Windows or random() on POSIX systems.
Generating Random Numbers in Excel
Excel has two primary functions: RAND() returns a uniform random number between 0 and 1, and RANDBETWEEN(bottom, top) returns a random integer between the specified bounds (inclusive). For example, =RANDBETWEEN(1, 100) gives a random integer from 1 to 100. To generate a random decimal between two values, use =RAND()*(max-min)+min. These functions recalculate every time the worksheet recalculates (e.g., when you press F9). To keep a static value, copy the cell and paste as values (Ctrl+Shift+V on Windows, Cmd+Shift+V on Mac). For a random sample from a list, combine with INDEX and RANDBETWEEN.
Common Pitfalls and How to Avoid Them
- Modulo bias: Using
rand() % ncan skew results ifndoes not divideRAND_MAX. Userand() / (RAND_MAX / n + 1)or rejection sampling. - Seeding incorrectly: If you seed with a constant, you get the same sequence every run. Use
time(0)or a better entropy source. - Using random for security:
rand()is not cryptographically secure. Usesecretsin Python orCryptGenRandomon Windows. - Excel recalculation:
RAND()andRANDBETWEENrecalculate on every change, which can be annoying. UseApplication.Volatilein VBA or paste values.
Comparing Randomness in Different Languages
Python’s random is easy and suitable for simulations, but not for cryptography. C’s rand() is fast but has limited range and potential bias. Excel’s functions are fine for quick tasks but not for high-volume simulations. For scientific work, use NumPy’s numpy.random which offers many distributions. For cryptography, use language-specific secure APIs. Always check the documentation for the specific version you’re using.
Frequently Asked Questions
How do I generate a random number in a specific range?
In Python, use random.randint(a, b) for integers or random.uniform(a, b) for floats. In C, use rand() % (b - a + 1) + a but be aware of bias; or use rand() / (RAND_MAX / (b - a + 1) + 1). In Excel, use =RANDBETWEEN(a, b).
Why do I get the same random numbers every time?
Because the PRNG is seeded with the same value. In C, if you don’t call srand(time(0)), the default seed is 1, giving the same sequence. In Python, if you don’t seed, the system uses OS entropy, but if you call random.seed(42), you get the same sequence. In Excel, the functions recalculate, but if you copy and paste values, they become static.
Can I generate truly random numbers?
Yes, using hardware random number generators or services like random.org, which use atmospheric noise. In code, you can use os.urandom() in Python, which reads from /dev/urandom on Linux, or secrets module for cryptographic use.
How do I generate a random sample from a list?
In Python, use random.sample(list, k) to get k unique elements, or random.choices(list, k=k) for duplicates allowed. In Excel, use =INDEX(A:A, RANDBETWEEN(1, COUNTA(A:A))) for one random item, or use Data Analysis Toolpak for a sample.
What is the difference between random and pseudo-random?
Random numbers are unpredictable and non-reproducible, often from physical sources. Pseudo-random numbers are generated by algorithms and are deterministic given a seed. For most applications, pseudo-random is sufficient, but for security, you need cryptographically secure pseudo-randomness.
Related
- JavaScript Get Random Number: Math.random() Explained
- Cool Shortcut Keys: 30+ Time-Savers for Windows
- Data Entry Job Information: Work, Pay & Safety
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 Create a Mail Signature in Outlook on Any DeviceTo create a mail signature in Outlook, open the signature settings for the account you use, create and…
- Snowflake to Number: Convert with TO_NUMBER & CASTThe direct answer: use the TO_NUMBER function (alias TO_DECIMAL, TO_NUMERIC) or the CAST expression to convert a string…
- Group Rows in Excel: Keyboard Shortcut and StepsTo group rows in Excel for Microsoft 365 on Windows, select the row headers you want to group…
- Google Sheets Date Difference: Formulas and ExamplesTo calculate the number of days between two dates in Google Sheets, subtract the earlier date from the…
- Leading Zeros in Excel: How to Keep ThemTo keep a leading zero in Excel, store the entry as text or apply a custom number format…
- SQL COUNT DISTINCT: Syntax, Examples, and PitfallsIn Microsoft SQL Server, COUNT(DISTINCT column_name) returns the number of unique, non-NULL values in a column or expression.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.