How Random Numbers Are Generated in Code — Are They Truly Random?

https://www.magnific.com/free-photo/computer-program-coding-screen_18415585.htm#fromView=keyword&page=1&position=0&uuid=17df6075-e28d-4926-8d99-6c313a9e9ff9&track=ais_hybrid&query=Coding

 

Almost every Computer Engineering student writes a program using rand() during their first few semesters—whether to simulate a dice roll, shuffle a deck of cards, or generate dummy sensor readings. It feels like magic: you call one function, and the computer gives you an unpredictable number.

Yet if you stop and think about how computers actually work, a puzzle emerges. Computers are strictly logical, predictable machines. If you give a processor the exact same instructions and the exact same inputs, it will produce the exact same result every single time. So how does a completely predictable machine generate “random” numbers—and are they actually random?

How Randomness Works in General

In computing, there are two completely different ways to generate random numbers: faking it with math or measuring the physical world.

Pseudo-Random Numbers (PRNG): The “Math Recipe” Approach

Most of the time when your code generates a random number, it is not truly random. Instead, it uses a Pseudo-Random Number Generator (PRNG)—a mathematical formula that takes a starting number (called a seed) and scrambles it to produce a sequence of numbers that looks random.

Think of a PRNG like a giant book filled with millions of pre-written numbers:

  • The seed tells the computer which page to open first.
  • Every time you ask for a random number, the computer reads the next number on the page.
  • If you start on the exact same page (the same seed), you will read the exact same sequence of numbers every time.

Because this approach only relies on math, it is extremely fast and great for video games, animations, and simulations. However, because it follows a formula, anyone who figures out your starting seed can predict every number your program will generate next.

True Random Numbers (TRNG): The “Real-World Noise” Approach

To get true randomness, a computer has to step outside of pure math and measure unpredictable things happening in the physical world. A True Random Number Generator (TRNG) uses specialized hardware to capture tiny, chaotic physical events—such as:

  • Electrical static (thermal noise) inside a chip’s circuits
  • Slight timing jitters in electronic oscillators
  • Unpredictable user behavior, like the exact millisecond you press a key or move a mouse

Because nature itself is unpredictable at the microscopic level, nobody can calculate or guess the next number from a TRNG.

Security Note (CSPRNG): For security tasks like banking, Wi-Fi encryption, or passwords, modern systems use Cryptographically Secure PRNGs (CSPRNGs)—which collect real-world noise from your operating system and feed it into heavy-duty cryptographic algorithms so attackers cannot guess the output.

What Does It Do in C and C++?

In Computer Engineering courses, C and C++ are our core languages because they sit close to the hardware. Understanding how both handle randomness shows the difference between old-school math tricks and modern hardware-aware code.

C (<stdlib.h>): rand() and srand()

In C, rand() uses a classic math formula (called a Linear Congruential Generator) that multiplies and adds numbers behind the scenes to create the next value.

However, rand() has a famous catch: if you do not give it a seed using srand(), it defaults to a seed of 1 every single time. That means your program will print the exact same “random” numbers every time you run it! To fix this, programmers usually seed it with the current system clock (time(NULL)).

C EXAMPLE (<STDLIB.H>)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
// Seed the generator using the current time in seconds.
// Without this line, rand() produces the exact same numbers every run!
srand((unsigned int)time(NULL));

for (int i = 0; i < 5; i++) {
// Generate a number between 1 and 6 (like a dice roll)
int dice = (rand() % 6) + 1;
printf(“Roll %d: %d\n”, i + 1, dice);
}

return 0;
}

 

Why C’s rand() is not truly random:

  • It is 100% deterministic math.
  • Because time(NULL) only changes once per second, running the program twice within the same second gives identical results.

Modern C++ (<random>): Better Math + Real Hardware Entropy

Because C’s rand() is easy to predict and has statistical flaws, modern C++ introduced the <random> library. It gives you two important tools:

  • std::random_device: Asks your CPU or operating system for true physical randomness.
  • std::mt19937 (Mersenne Twister): A much stronger mathematical generator that only repeats its pattern after an astronomically huge cycle.
MODERN C++ EXAMPLE (<RANDOM>)

#include <iostream>
#include <random>

int main() {
// 1. Ask the hardware/OS for a true random seed
std::random_device rd;

// 2. Feed that seed into a high-quality C++ random engine
std::mt19937 gen(rd());

// 3. Cleanly map the result to a fair range from 1 to 6
std::uniform_int_distribution<int> dice(1, 6);

for (int i = 0; i < 5; ++i) {
std::cout << “Roll ” << (i + 1) << “: ” << dice(gen) << ‘\n’;
}

return 0;
}

 

In this C++ setup, you get the best of both worlds: std::random_device provides an unpredictable starting point from hardware, and std::mt19937 rapidly generates clean, evenly distributed numbers.

How Other Languages Handle It: Python, Java, and Beyond

High-level and embedded languages follow the exact same principle: they separate fast math-based randomness (for everyday apps) from real OS/hardware randomness (for security).

Python: random vs. secrets

Python makes this distinction very clear by giving programmers two different modules:

  • random: Uses a fast math formula (the same Mersenne Twister algorithm used in C++). It is great for data science, games, and testing, and you can lock its seed if you want repeatable results.
  • secrets: Pulls real randomness directly from your operating system. You should always use this when generating passwords, API keys, or login tokens.
PYTHON EXAMPLE (RANDOM VS. SECRETS)

import random
import secrets

# 1. Everyday pseudo-random (math-based, fast, repeatable if seeded)
print(“Everyday random:”, random.randint(1, 100))

# 2. Cryptographically secure random (OS noise-based, unpredictable)
print(“Secure random:”, secrets.randbelow(100) + 1)
print(“Secure password token:”, secrets.token_hex(8))

 

Java: Random vs. SecureRandom

Java uses the same two-tier design:

  • util.Random: Uses a fast 48-bit math formula. It automatically seeds itself using your system clock, making it convenient for general software logic, though a determined attacker could still reverse-engineer the formula.
  • security.SecureRandom: Connects directly to your operating system’s security provider to gather unpredictable system entropy.
JAVA EXAMPLE (RANDOM VS. SECURERANDOM)

import java.util.Random;
import java.security.SecureRandom;

public class RandomExample {
public static void main(String[] args) {
// Standard PRNG (fast math formula)
Random standardRng = new Random();
System.out.println(“Standard Random: ” + standardRng.nextInt(100));

// Cryptographically Secure RNG (backed by OS entropy)
SecureRandom secureRng = new SecureRandom();
System.out.println(“Secure Random: ” + secureRng.nextInt(100));
}
}

 

Bonus: Microcontrollers (ESP-IDF) & Mobile Apps (Dart)

  • ESP-IDF (Embedded C on ESP32): Because an ESP32 microcontroller has physical radio (Wi-Fi/Bluetooth) and analog-to-digital circuits on the chip, calling esp_random() actually reads real electrical thermal noise from the silicon—giving embedded engineers a built-in True Random Number Generator!
  • Dart / Flutter: Dart uses Random() from dart:math for fast software-generated numbers in UI animations and games, while secure() asks the phone or computer’s operating system for genuine cryptographic randomness.

 

Quick Summary Comparison

Language / Platform Everyday Function (Math-Based) Secure / True Function (Hardware / OS) Is It Truly Random?
C rand() OS-specific APIs No — Purely deterministic math
C++ std::mt19937 std::random_device Only random_device (when hardware-backed)
Python random.randint() secrets.randbelow() Only secrets (uses OS entropy)
Java java.util.Random java.security.SecureRandom Only SecureRandom (uses OS entropy)
ESP-IDF (ESP32) rand() esp_random() Yes — Reads chip electrical noise
Dart / Flutter Random() Random.secure() Only Random.secure() (uses OS entropy)

 

Conclusion

So, is rand() truly random? No. By default, almost every programming language relies on deterministic math formulas because they are fast, lightweight, and even helpful when you need to reproduce bugs during testing.

However, when real unpredictability matters—such as encrypting wireless IoT data, generating user passwords, or securing authentication tokens—software math is not enough. That is where Computer Engineering shines: bridging software code with physical hardware noise to turn a predictable machine into a source of genuine randomness.

 

References

  1. cppreference.com: C++ Numerics Library — Pseudo-random number generation (<random>) — https://en.cppreference.com/w/cpp/numeric/random
  2. Matsumoto, M., & Nishimura, T. (1998): Mersenne Twister: A 623-Dimensionally Equidistributed Uniform Pseudo-Random Number Generator, ACM Transactions on Modeling and Computer Simulation, Vol. 8, No. 1, pp. 3–30 — https://dl.acm.org/doi/10.1145/272991.272995
  3. Python Software Foundation: random — Generate pseudo-random numbers & secrets — Generate secure random numbers — https://docs.python.org/3/library/random.html | https://docs.python.org/3/library/secrets.html
  4. Oracle Java Documentation: Class SecureRandom (java.security.SecureRandom) — https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html
  5. Espressif Systems: ESP-IDF Programming Guide — Random Number Generation (esp_random) — https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/random.html
  6. Dart API Documentation: Random class (dart:math) — https://api.dart.dev/dart-math/Random-class.html