Random Number Generation Code: How It Works

How-to basics · Updated November 23, 2026

The short answer: in most programming languages, you call a built-in function such as Math.random() in JavaScript, random.randint() in Python, or rand() in C. These functions return a number that appears random, but the details matter if you need security, fairness, or reproducibility. This article explains what random number generation code actually does, how to choose the right function, and common pitfalls.

What Is a Random Number, Really?

A random number is a value drawn from a set of possible values where each outcome has a known probability, and the outcome cannot be predicted from previous outcomes. True randomness comes from physical processes like radioactive decay or atmospheric noise. Most software uses pseudo-random number generators (PRNGs), which are algorithms that produce sequences that look random but are actually deterministic—given the same starting point, they produce the same sequence.

The starting point is called the seed. If you set the seed explicitly, you get reproducible results, which is useful for testing. If you don’t set it, the system uses an unpredictable source like the current time or system entropy.

How Random Number Generation Works in Code

Here are the most common functions in popular languages:

  • JavaScript: Math.random() returns a floating-point number between 0 (inclusive) and 1 (exclusive). To get an integer between 1 and 10, use Math.floor(Math.random() * 10) + 1.
  • Python: random.randint(1, 10) returns an integer between 1 and 10 inclusive. random.random() returns a float between 0 and 1.
  • C: rand() returns an integer between 0 and RAND_MAX (often 32767). Use modulo to limit the range, but beware of bias unless you use a rejection method.
  • Java: Math.random() works like JavaScript, but Random.nextInt(n) is preferred for integers because it avoids bias.
  • C#: Random.Next(min, max) returns an integer in the range [min, max).

For example, in Python, to simulate a dice roll:

import random
roll = random.randint(1, 6)
print(roll)

Choosing the Right Random Function

Not all random functions are equal. The choice depends on your use case:

  1. General purpose: For games, simulations, or any non-security use, the standard PRNG in your language is fine. Python’s random module uses the Mersenne Twister, which is fast and has a long period.
  2. Security-sensitive: For passwords, tokens, or encryption, use a cryptographically secure PRNG (CSPRNG). In Python, that’s secrets module; in JavaScript, crypto.getRandomValues(); in C, arc4random() or getrandom().
  3. Reproducible results: If you need the same sequence every run, set a seed. In Python: random.seed(42). In JavaScript, there is no built-in seedable PRNG; you need a custom algorithm like mulberry32.

For example, to generate a secure random password in Python:

import secrets
import string
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for _ in range(12))

Common Pitfalls and Misconceptions

One common mistake is using Math.random() for security. It is not cryptographically secure—an attacker can predict the sequence if they know the seed. Another pitfall is modulo bias when using rand() % n in C. If RAND_MAX is not evenly divisible by n, some numbers are more likely than others. For example, if RAND_MAX is 32767 and you want a number 0–9, the values 0–7 appear slightly more often than 8–9.

Another misconception: “random” does not mean “uniform” unless you specify it. Math.random() is uniform, but many real-world processes are not. Also, generating a random integer by multiplying a float and rounding can introduce bias if not done carefully.

Finally, don’t re-seed every time you call the function. Seeding with the current time repeatedly can produce identical numbers if calls happen in the same millisecond.

Security and True Randomness

For security-critical applications, use a CSPRNG. These use entropy from the operating system (e.g., /dev/urandom on Linux). In Python, the secrets module is designed for this. In JavaScript, crypto.getRandomValues() is available in browsers and Node.js. For example:

// JavaScript secure random integer 1-100
const array = new Uint32Array(1);
crypto.getRandomValues(array);
const randomInt = (array[0] % 100) + 1;

True random number generators (TRNGs) use hardware or physical phenomena. They are rarely needed in software because CSPRNGs are practically unpredictable. If you ever need true randomness, you can use a service like random.org, but that requires network access and is not suitable for offline code.

Random Numbers in Spreadsheets

In Excel, the function RAND() returns a random decimal between 0 and 1. To get an integer between 1 and 10, use =INT(RAND()*10)+1. In Google Sheets, RAND() works the same. For reproducible results, you can use RANDARRAY in Excel 365 to generate a range of random numbers. For example, =RANDARRAY(5,1,1,10,TRUE) returns 5 integers between 1 and 10. Note that RAND() recalculates every time the sheet changes, which can be annoying; use RANDBETWEEN(1,10) for integers directly. In Excel, RANDBETWEEN is volatile too, so copy and paste as values if you need to freeze the numbers.

Frequently Asked Questions

Q: How do I generate a random number between 1 and 100 in JavaScript?
A: Use Math.floor(Math.random() * 100) + 1. This gives an integer from 1 to 100 inclusive. Remember that Math.random() returns a float from 0 (inclusive) to 1 (exclusive), so multiplying by 100 gives 0 to 99.999…, and flooring gives 0–99, then adding 1 shifts to 1–100.

Q: Why is Math.random() not secure?
A: Math.random() uses a PRNG with a seed that is not unpredictable enough. If an attacker can estimate the seed or observe enough outputs, they can predict future values. For anything involving passwords, tokens, or encryption, use crypto.getRandomValues() instead.

Q: Can I make a random number generator that is reproducible?
A: Yes, by setting a seed. In Python, random.seed(123) makes the sequence repeatable. In Excel, you can use RANDARRAY with a seed? Actually, Excel does not support seeding directly; you can use VBA to set a seed or use a custom function. In JavaScript, you need a custom PRNG like mulberry32 that takes a seed.

Q: What is modulo bias and how do I avoid it?
A: Modulo bias occurs when you use rand() % n and the range of rand() is not a multiple of n. Some outputs are more likely. To avoid it, use a rejection sampling method: generate a random number, if it’s above the largest multiple of n, reject and try again. Or use a function that handles it, like random.randint() in Python.

Q: How do I generate a random decimal between 0 and 1 in Excel?
A: Use =RAND(). It returns a uniform random number between 0 and 1. To get a decimal between 5 and 10, use =RAND()*5+5.

Q: Is there a way to get a truly random number in code?
A: Yes, but it’s rare. You can use hardware random number generators (e.g., Intel’s RDRAND) or services like random.org. Most applications don’t need true randomness; a CSPRNG is sufficient.

Alternatives and Best Practices

If you need random numbers in bulk, consider using a library like numpy.random in Python, which is faster and offers more distributions. For simulations, use a well-tested PRNG like the Mersenne Twister (Python’s default) or PCG. For reproducibility, always set a seed and document it. For security, use the operating system’s CSPRNG. And always test your random number generator for uniformity if it matters—for example, by running a chi-squared test.

In summary, the code to generate a random number is simple, but the right choice depends on your context. Use the standard function for everyday tasks, a secure one for sensitive data, and a seeded one for reproducible experiments.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.