Random Number Code Examples
Integers in a range, lists of numbers and decimals in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go
Each example below draws a whole number from 1 to 100, a list of ten such numbers and a decimal between 0 and 100, and most also show the secure variant. The guide covers the three things that make these snippets correct or subtly wrong: where the range ends, how raw random bits are mapped onto it, and which generator the job calls for. Prefer no code? The interactive Numbers generator does the same in the browser.
Inclusive and exclusive bounds
“A number from 1 to 100” has 100 possible outcomes, and every language spells that range differently. PHP's random_int(1, 100), Python's randint(1, 100) and Ruby's rand(1..100) include both ends. Java's nextInt(100), Go's rand.IntN(100) and Python's secrets.randbelow(100) return 0 to 99, so the examples add 1. C#'s Next(1, 101), Java's nextInt(1, 101) and NumPy's randint(1, 101) take an exclusive upper bound, which is why 101 appears in them. Mixing these conventions is the most frequent source of a die that never rolls 6 or a lottery draw that can return 0.
From random bits to a fair range
Generators produce raw bits or a float in [0, 1). Turning that into 1–100 fairly takes care:
- Modulo bias. A random byte (0–255) taken
% 100gives 0–55 three ways each and 56–99 only two ways, so the low values come up 50% more often. With a 32-bit source the skew shrinks to about one part in 43 million for a range of 100, but it grows with the range. Library functions such asrandom_int,randbelow,nextInt(bound)andGetInt32remove it by rejection sampling: they discard draws from the incomplete top block and draw again. - Float scaling.
Math.floor(Math.random() * 100) + 1is fair because the float never reaches 1.0. Rounding instead of flooring gives the two end values half the weight of the others. - Decimals. A double carries 53 bits of precision, more than enough for 0–100 with two decimals. Drawing an integer from 0 to 10,000 and dividing by 100, as the PHP example does, gives exactly 10,001 evenly weighted values and avoids floating-point surprises when the result is stored as a price or score.
Which generator to use
Simulations, games, shuffled test fixtures and sampling need speed and, often, reproducibility: the default generators (Math.random(), Python's random, java.util.Random, std::mt19937, math/rand/v2) are fine, and seeding them with a fixed value replays the exact same sequence, which is what a failing Monte Carlo test needs. Mersenne Twister, behind Python's random and mt19937, can be fully reconstructed from 624 consecutive 32-bit outputs, so it must not decide anything worth predicting.
Use the operating system's secure source when a number protects or awards something: one-time codes, PINs, giveaway winners, card deals in real-money games. That means random_int(), crypto.getRandomValues(), secrets, SecureRandom, RandomNumberGenerator or crypto/rand. A 6-digit code from these has exactly 1,000,000 equally likely values; the same code from a seeded PRNG may have far fewer if the seed is guessable.
Common mistakes
- Reseeding inside a loop. Seeding from the clock on every call returns the same number many times within one millisecond. Create the generator once and reuse it.
- Expecting no repeats. Ten independent draws from 1–100 contain a duplicate about 37% of the time. For distinct values, shuffle the range and take the first ten, or draw a sample without replacement.
- Using
rand() % nin C or C++.RAND_MAXcan be as low as 32,767, which both limits the range and amplifies modulo bias. - Treating a seed as a secret. A 32-bit seed can be brute-forced in seconds, so anything derived from it is only as unpredictable as those 32 bits.
Common Use Cases
- Dice rolls, card shuffles and loot tables in games
- Lottery and raffle number picks, and drawing giveaway winners
- Monte Carlo simulations and statistical sampling, reproducible with a fixed seed
- Random assignment for A/B tests and train/test data splits
- Test data and fuzzing inputs for QA and unit tests
- One-time numeric codes and PINs (secure generator only)
Random Number Code Examples in PHP
Generate cryptographically secure random numbers in PHP using the random_int() function. This modern approach provides better security than older methods like rand() or mt_rand().
<?php
// Generate a single random number between 1 and 100
$randomNumber = random_int(1, 100);
echo $randomNumber; // Example output: 42
// Generate multiple random numbers
$numbers = [];
for ($i = 0; $i < 10; $i++) {
$numbers[] = random_int(1, 100);
}
print_r($numbers);
// Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
// Generate random float/decimal
$randomFloat = random_int(0, 10000) / 100; // 0.00 to 100.00
echo number_format($randomFloat, 2); // Example: 42.17
How it works in PHP
The random_int() function generates cryptographically secure random integers. It takes two parameters: the minimum and maximum values (inclusive). For random floats, divide a large random integer by a power of 10 to get the desired precision.
Sample output
42
Array
(
[0] => 23
[1] => 7
[2] => 91
[3] => 45
[4] => 12
[5] => 68
[6] => 3
[7] => 89
[8] => 54
[9] => 31
)
42.17
PHP notes
random_int()(PHP 7.0+) is secure and includes both bounds; it throws aValueErrorif min is greater than max.- Since PHP 7.1
rand()is an alias ofmt_rand(), a Mersenne Twister: fine for games, not for codes. - PHP 8.2+ adds
Random\Randomizer, whosegetInt()andgetFloat()(8.3) work with a seedable engine such asXoshiro256StarStaror the default secure one.
Random Number Code Examples in JavaScript
Generate random numbers in JavaScript using Math.random() for general purposes or crypto.getRandomValues() for cryptographically secure random numbers.
// Generate a random number between 1 and 100
const randomNumber = Math.floor(Math.random() * 100) + 1;
console.log(randomNumber); // Example output: 42
// Generate multiple random numbers
const numbers = Array.from({ length: 10 }, () =>
Math.floor(Math.random() * 100) + 1
);
console.log(numbers);
// Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
// Generate cryptographically secure random number
const secureRandom = () => {
const array = new Uint32Array(1);
crypto.getRandomValues(array);
return array[0] / (0xFFFFFFFF + 1); // Normalize to 0-1
};
const secureNumber = Math.floor(secureRandom() * 100) + 1;
console.log(secureNumber); // Example: 67
// Random decimal between 0 and 100
const randomFloat = (Math.random() * 100).toFixed(2);
console.log(randomFloat); // Example: 42.17
How it works in JavaScript
Math.random() returns a decimal between 0 (inclusive) and 1 (exclusive). Multiply by your range and use Math.floor() to get integers. For security-critical applications (tokens, cryptography), use crypto.getRandomValues() which provides cryptographically strong random values.
Sample output
42 [23, 7, 91, 45, 12, 68, 3, 89, 54, 31] 67 42.17
JavaScript notes
Math.random()returns a double in [0, 1); engines such as V8 use xorshift128+, which is fast but predictable.crypto.getRandomValues()fills at most 65,536 bytes per call and throws aQuotaExceededErrorbeyond that.- Node.js 19+ exposes the Web Crypto
cryptoobject as a global; on older versions userequire('node:crypto').webcryptoorcrypto.randomInt(1, 101)(exclusive upper bound). - JavaScript has no built-in seeded generator; reproducible sequences need a small library or your own PRNG.
Random Number Code Examples in Python
Generate random numbers in Python using the random module for general purposes or the secrets module for cryptographically secure random numbers.
import random
import secrets
# Generate a single random number between 1 and 100
random_number = random.randint(1, 100)
print(random_number) # Example output: 42
# Generate multiple random numbers
numbers = [random.randint(1, 100) for _ in range(10)]
print(numbers)
# Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
# Generate cryptographically secure random number
secure_number = secrets.randbelow(100) + 1 # 1 to 100
print(secure_number) # Example: 67
# Random float between 0 and 100
random_float = random.uniform(0, 100)
print(f"{random_float:.2f}") # Example: 42.17
# Using NumPy for array generation
import numpy as np
numpy_numbers = np.random.randint(1, 101, size=10)
print(numpy_numbers)
# Example output: [23 7 91 45 12 68 3 89 54 31]
How it works in Python
random.randint(a, b) returns a random integer between a and b (both inclusive). The secrets module provides cryptographically secure random numbers suitable for security-sensitive applications. For large-scale numerical work, use NumPy's numpy.random module.
Sample output
42 [23, 7, 91, 45, 12, 68, 3, 89, 54, 31] 67 42.17 [23 7 91 45 12 68 3 89 54 31]
Python notes
random.randint(a, b)includesb, whilerandom.randrange(a, b)andsecrets.randbelow(n)exclude it.random.seed(42)replays the module-level generator;random.Random(42)gives an independent instance per test or thread.- NumPy now recommends
np.random.default_rng(seed).integers(1, 101, size=10)over the legacynp.random.randintshown above.
Random Number Code Examples in Java
Generate random numbers in Java using the Random class, ThreadLocalRandom for better performance, or SecureRandom for cryptographically secure random numbers.
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.security.SecureRandom;
import java.util.stream.IntStream;
public class RandomNumberExample {
public static void main(String[] args) {
// Generate a single random number between 1 and 100
Random random = new Random();
int randomNumber = random.nextInt(100) + 1;
System.out.println(randomNumber); // Example output: 42
// Generate multiple random numbers (Java 8+)
int[] numbers = IntStream.generate(() ->
ThreadLocalRandom.current().nextInt(1, 101)
).limit(10).toArray();
System.out.println(java.util.Arrays.toString(numbers));
// Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
// Generate cryptographically secure random number
SecureRandom secureRandom = new SecureRandom();
int secureNumber = secureRandom.nextInt(100) + 1;
System.out.println(secureNumber); // Example: 67
// Random double between 0 and 100
double randomDouble = random.nextDouble() * 100;
System.out.printf("%.2f%n", randomDouble); // Example: 42.17
}
}
How it works in Java
Random.nextInt(n) returns a value from 0 (inclusive) to n (exclusive), so add your minimum value. ThreadLocalRandom is preferred for concurrent applications as it reduces contention. SecureRandom provides cryptographically strong random numbers but is slower.
Sample output
42 [23, 7, 91, 45, 12, 68, 3, 89, 54, 31] 67 42.17
Java notes
ThreadLocalRandom.current().nextInt(1, 101)takes an exclusive upper bound and avoids contention between threads.new Random(seed)gives the same sequence on every JVM; seeding aSecureRandomdoes not make it reproducible on most providers, so keep it out of repeatable tests.SecureRandom.getInstanceStrong()can block on Linux while it waits for entropy; plainnew SecureRandom()is the right default for servers.- Java 17+ offers the
RandomGeneratorinterface and algorithms such asL64X128MixRandomviaRandomGenerator.of().
Random Number Code Examples in C#
Generate random numbers in C# using the Random class for general purposes or RandomNumberGenerator for cryptographically secure random numbers in .NET applications.
using System;
using System.Security.Cryptography;
using System.Linq;
class RandomNumberExample
{
static void Main()
{
// Generate a single random number between 1 and 100
Random random = new Random();
int randomNumber = random.Next(1, 101);
Console.WriteLine(randomNumber); // Example output: 42
// Generate multiple random numbers
int[] numbers = Enumerable.Range(0, 10)
.Select(_ => random.Next(1, 101))
.ToArray();
Console.WriteLine($"[{string.Join(", ", numbers)}]");
// Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
// Generate cryptographically secure random number
int secureNumber = RandomNumberGenerator.GetInt32(1, 101); // 1 to 100, .NET Core 3.0+
Console.WriteLine(secureNumber); // Example: 67
// Random double between 0 and 100
double randomDouble = random.NextDouble() * 100;
Console.WriteLine($"{randomDouble:F2}"); // Example: 42.17
}
}
How it works in C#
Random.Next(min, max) returns an integer from min (inclusive) to max (exclusive), which is why the examples pass 101. NextDouble() gives a double in [0, 1) to scale for decimals. For a secure number, RandomNumberGenerator.GetInt32(min, max) draws from the operating system's cryptographic generator without modulo bias. LINQ builds the array of ten numbers.
Sample output
42 [23, 7, 91, 45, 12, 68, 3, 89, 54, 31] 67 42.17
C# notes
- A single
Randominstance is not thread-safe; on .NET 6+ useRandom.Sharedfrom several threads. - On .NET Framework, two
new Random()created in the same few milliseconds get the same clock seed; .NET Core and later seed each instance randomly. RandomNumberGenerator.GetInt32needs .NET Core 3.0+ or .NET Standard 2.1; on .NET Framework, avoidMath.Abs(int)on random bytes, which throws forint.MinValue.
Random Number Code Examples in C++
Generate random numbers in C++ using the modern <random> library with uniform_int_distribution and mt19937 for high-quality random number generation.
#include <iostream>
#include <random>
#include <iomanip>
#include <vector>
int main() {
// Initialize random number generator
std::random_device rd; // Seed
std::mt19937 gen(rd()); // Mersenne Twister engine
std::uniform_int_distribution<> distrib(1, 100);
// Generate a single random number between 1 and 100
int randomNumber = distrib(gen);
std::cout << randomNumber << std::endl; // Example output: 42
// Generate multiple random numbers
std::vector<int> numbers;
for (int i = 0; i < 10; ++i) {
numbers.push_back(distrib(gen));
}
std::cout << "[";
for (size_t i = 0; i < numbers.size(); ++i) {
std::cout << numbers[i];
if (i < numbers.size() - 1) std::cout << ", ";
}
std::cout << "]" << std::endl;
// Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
// Random double between 0 and 100
std::uniform_real_distribution<> realDistrib(0.0, 100.0);
double randomDouble = realDistrib(gen);
std::cout << std::fixed << std::setprecision(2) << randomDouble << std::endl;
// Example: 42.17
return 0;
}
How it works in C++
Modern C++ (C++11+) provides the <random> library with uniform_int_distribution for uniform random integers and mt19937 (Mersenne Twister) for high-quality pseudo-random number generation. random_device provides non-deterministic seeds.
Sample output
42 [23, 7, 91, 45, 12, 68, 3, 89, 54, 31] 42.17
C++ notes
std::uniform_int_distribution<>(1, 100)includes both bounds, unlike most other languages' integer functions.- Create the engine and distribution once; constructing
std::random_deviceand seeding a newmt19937on every call is slow. - Distribution algorithms are implementation-defined, so the same seed can give different numbers with libstdc++, libc++ and MSVC; the raw
mt19937output is portable.
Random Number Code Examples in Ruby
Generate random numbers in Ruby using rand() for general purposes or SecureRandom for cryptographically secure random numbers in Ruby and Rails applications.
require 'securerandom'
# Generate a single random number between 1 and 100
random_number = rand(1..100)
puts random_number # Example output: 42
# Generate multiple random numbers
numbers = Array.new(10) { rand(1..100) }
puts numbers.inspect
# Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
# Generate cryptographically secure random number
secure_number = SecureRandom.random_number(1..100)
puts secure_number # Example: 67
# Random float between 0 and 100
random_float = rand(0.0..100.0)
puts format('%.2f', random_float) # Example: 42.17
# Using Random class for reproducible results
prng = Random.new(42) # Seeded for reproducibility
seeded_number = prng.rand(1..100)
puts seeded_number
How it works in Ruby
rand(range) generates random numbers within a range. SecureRandom provides cryptographically secure random numbers suitable for security tokens and keys. The Random class allows seeded random generation for reproducible results.
Sample output
42 [23, 7, 91, 45, 12, 68, 3, 89, 54, 31] 67 42.17
Ruby notes
rand(1..100)includes 100,rand(1...100)excludes it, andrand(100)returns 0 to 99.SecureRandom.random_number(1..100)accepts the same range forms asrand.Random.new(42)gives an isolated, reproducible generator;Kernel#randuses the default generator.(1..100).to_a.sample(10)draws ten distinct numbers; passrandom: SecureRandomfor a secure draw.
Random Number Code Examples in Go
Generate random numbers in Go using math/rand for general purposes or crypto/rand for cryptographically secure random numbers in Go applications.
package main
import (
cryptorand "crypto/rand"
"fmt"
"math/big"
"math/rand/v2"
)
func main() {
// Generate a single random number between 1 and 100
randomNumber := rand.IntN(100) + 1
fmt.Println(randomNumber) // Example output: 42
// Generate multiple random numbers
numbers := make([]int, 10)
for i := range numbers {
numbers[i] = rand.IntN(100) + 1
}
fmt.Println(numbers)
// Example output: [23 7 91 45 12 68 3 89 54 31]
// Generate cryptographically secure random number
nBig, _ := cryptorand.Int(cryptorand.Reader, big.NewInt(100))
secureNumber := nBig.Int64() + 1
fmt.Println(secureNumber) // Example: 67
// Random float between 0 and 100
randomFloat := rand.Float64() * 100
fmt.Printf("%.2f\n", randomFloat) // Example: 42.17
}
How it works in Go
The example imports math/rand/v2 (Go 1.22+) as rand and crypto/rand as cryptorand, because both packages are named rand and Go rejects the duplicate import. rand.IntN(n) returns 0 to n−1, so the code adds 1, and rand.Float64() returns a float in [0, 1). cryptorand.Int(cryptorand.Reader, big.NewInt(100)) returns a secure *big.Int from 0 to 99.
Sample output
42 [23 7 91 45 12 68 3 89 54 31] 67 42.17
Go notes
math/rand/v2needs no seeding; its top-level functions are safe for concurrent use.- For a reproducible sequence create
rand.New(rand.NewPCG(seed1, seed2)). - In the v1
math/randpackage the global source is seeded automatically since Go 1.20 andrand.Seedis deprecated.
Try the Interactive Generator
Need values right now rather than code? The Numbers generator runs in the browser and exports to TXT, CSV or JSON.
OPEN THE NUMBERS GENERATOR →