SoFunction
Updated on 2025-04-14

Detailed explanation of true and false random numbers in Java

Pseudo-random number

definition: Pseudorandom Number is a number generated by an algorithm. It seems random, but is actually deterministic.

Generate method: Usually using mathematical formulas or algorithms, such as linear congruence, to generate a sequence based on an initial value (seed).

Features

  • Reproducibility: Given the same seed, the pseudo-random number generator will always produce the same sequence of numbers. This is very useful for testing and debugging.
  • High efficiency: Fast generation speed, suitable for scenarios where a large number of random numbers are required.
  • Periodicity: The sequence is finite long and will be repeated in the end.

Application scenarios: Suitable for simulation, numerical analysis, game development and other fields that do not require absolute randomness.

True random number

definition: True Random Number depends on unpredictable physical phenomena, such as radioactive decay, thermal noise, etc.

Generate method: Unpredictable events in nature are usually collected through hardware devices.

Features

  • Non-reproducibility: The same sequence cannot be generated under the same conditions.
  • Unpredictability: There is no predictable pattern, it is really random.
  • High complexity: The generation process may be slow and requires special hardware support.

Application scenarios: used in areas with extremely high security requirements, such as cryptography, encryption key generation, etc.

Java pseudo-random number

In javaRandomClasses are tools used to generate pseudo-random numbers. Its underlying implementation relies on an algorithm called Linear Congruential Generator (LCG), a commonly used pseudo-random number generation algorithm.

Linear Congruent Generator (LCG)

LCG is an algorithm that generates random sequences through the following formula:

[ X_{n+1} = (a \times X_n + c) \mod m ]

in:

(X) is a sequence of random numbers.

( a ), ( c ), and ( m ) are constants:

  • (m) is the modulus, usually a large prime number or a power of 2.
  • ( a ) is a multiplier.
  • ( c ) is increment.

(X_0) is the initial seed value.

Implementation of Java Random class

In Java,The class uses a 64-bit LGC algorithm, where:

  • Modulus ( m = 2^{48} )
  • Constant ( a = 25214903917 )
  • Increment ( c = 11 )

Each time a new random number is generated,RandomThe class updates the current seed to generate the next number.

Seed

  • initialization: If the seed is not specified,RandomSystem time will be used as the default seed.
  • Reproducibility: The same seed will produce the same sequence of random numbers, which is very useful for testing and debugging.

Internal method

Java RandomThe core method of the class isnext(int bits), used to generate a given number of random bits. Others such asnextInt(), nextDouble()All methods are based onnext(bits)To achieve it, just combine these bits in different ways.

protected int next(int bits) {
    long oldseed, nextseed;
    AtomicLong seed = ;
    do {
        oldseed = ();
        nextseed = (oldseed * 25214903917L + 11) & ((1L << 48) - 1);
    } while (!(oldseed, nextseed));
    return (int)(nextseed >>> (48 - bits));
}

Code explanation

1. Variable declaration

  • oldseed: Current seed value.
  • nextseed: Used to calculate the next seed value.
  • seed: oneAtomicLongType, used to ensure that threads safely update seeds.

2. Get the current seed value

oldseed = ();: From atomic variablesseedRead the current seed value.

3. Calculate the next seed value

nextseed = (oldseed * multiplier + addend) & mask;

Use the Linear Congruent Generator (LCG) formula to calculate the new seed value.

multiplieraddendandmaskis a constant, where:

  • multiplierIt is a multiplier.
  • addendIt is increment.
  • maskUsed to ensure that the results are within the valid range (usuallym-1,inmis modulus).

4. Update seed value

while (!(oldseed, nextseed));

  • usecompareAndSetMethod try tooldseedUpdated tonextseed
  • If other threads are modified during this periodseed,butcompareAndSetWill returnfalse, the cycle continues until successful. This mechanism ensures atomic updates in multi-threaded environments.

5. Generate random numbers

return (int)(nextseed >>> (48 - bits));

  • Move the new seed value right to get the number of random digits you want.
  • >>>The operator ensures that the left side is filled with zeros and the unsigned right is moved.
  • (48 - bits)Determines how many bits of random number to keep.

Summarize

This method uses seed values ​​and linear congruent generator algorithm to generate pseudo-random numbers and passAtomicLongEnsures thread safety in multi-threaded situations. It returns a random number in the form of an integer of the specified number of digits, which will be used by other methods such asnextInt()ornextDouble()Further processing is provided to the user with the required random number type.

Java true random number

In Java, realizing true random numbers usually requires relying on the functions of external hardware devices or operating systems, because pure software methods generate pseudo-random numbers.

use

AlthoughSecureRandomClasses are still pseudo-random in nature, but they can be configured to use entropy sources provided by the underlying operating system, so that the random numbers generated are close to true random numbers, especially in application scenarios where security requirements are high.

import ;

public class TrueRandomExample {
    public static void main(String[] args) {
        SecureRandom secureRandom = new SecureRandom();
        
        // Generate a random integer        int randomInt = ();
        ("Random Integer: " + randomInt);
        
        // Generate a random integer between 0 and 100        int boundedInt = (101);
        ("Bounded Random Integer (0-100): " + boundedInt);

        // Generate random byte array        byte[] randomBytes = new byte[16];
        (randomBytes);
        ("Random Bytes: " + (randomBytes));
    }
}

Features of SecureRandom

  • More sources of entropySecureRandomYou can use the entropy pool of the operating system (such as Linux's/dev/randomor/dev/urandom), these entropy sources collect uncertainties in the physical world.
  • Suitable for safe applications: Widely used in encryption, token generation and other occasions where high-quality random numbers are required.
  • Configurability: Allows specifying algorithms and providers to meet different security needs.

Hardware support for true random numbers

If true random numbers are needed, hardware random number generators (HRNGs) can be used, usually implemented through dedicated hardware devices, such as:

  • Intel's RDRAND instruction set: On supported processors, these instructions can directly provide hardware-level random numbers.
  • Other hardware devices: There are special USB interface random number generators on the market, which generate random numbers through physical phenomena such as thermal noise.

In Java, direct call to these hardware devices requires JNI (Java Native Interface) or the underlying operating system API, which involves calls and configurations of specific platforms. For most applications,SecureRandomIt has been able to provide sufficiently good random number quality.

Extension: How to understand thermal noise random numbers

Thermal noise random numbers are random numbers generated based on physical phenomena. Their main principle is to utilize thermal noise in electronic devices. Thermal noise, also known as Johnson-Nyquist noise, is caused by the voltage and current fluctuations caused by the thermal motion of free electrons in the conductor. This fluctuation is microscopically unpredictable and can therefore be used as a source of random numbers.

Key points of understanding the random numbers of thermal noise

Physical Basics

  • Thermal noise is generated by the random thermal motion of electrons in a conductor and is related to temperature.
  • This noise exists in all resistive conductors and cannot be completely eliminated.

Generation process

  • The thermal noise signal is amplified through an amplifier for measurement.
  • Analog signal is converted into digital signals using an analog-to-digital converter (ADC) to obtain a random binary number.

advantage

  • True randomness: Because thermal noise is caused by quantum mechanical effects, it is theoretically unpredictable, which makes it very suitable for security-related applications such as encryption key generation.
  • No repetitive: Each sample is independent and does not depend on any previous arbitrary value or state.

Application scenarios

Used for hardware random number generators (HRNGs), these devices are widely used in fields that require high security and high-quality random numbers, such as cryptography, secure communications, etc.

Implementation difficulties

  • Special hardware support is required, such as random number generation chips or devices.
  • The amplification and measurement of noise requires precise circuit design to ensure that ambient noise does not interfere with the results.

By understanding thermal noise and its application, we can better choose a random number generator that suits various needs. For general software applications, pseudo-random number generation is sufficient, while in highly secure situations, hardware-level true random number generation is required.

This is the end of this article about the detailed explanation of Java's real and false random numbers. For more relevant Java's real and false random numbers, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!