Storm29's blog

By Storm29, history, 4 hours ago, In English

Introduction

Random numbers play a crucial role in various fields such as simulations, games, cryptography, and statistical analysis. In C++, generating random numbers is simple, thanks to its built-in libraries. In this blog post, we'll explore how to generate random numbers and understand how the process works.

When generating random numbers without using the Standard Library (, , etc.), we need to dive into the actual algorithms used to create pseudo-random numbers. One of the most common methods is the Linear Congruential Generator (LCG), a simple algorithm that can generate a sequence of pseudo-random numbers.

The Linear Congruential Generator (LCG) Formula

The LCG formula is as follows:

Where: Xn is the current random number (also called the seed). a is the multiplier. c is the increment. m is the modulus (this is usually a large prime number or a power of two). X{n+1} is the next random number.

Here is a Sample code for better understanding.

Explanation of the Code

LCG Constants: The constants a, c, and m are chosen based on common values used for the LCG algorithm. Here, a = 1664525, c = 1013904223, and m = 2^32 (a large modulus for a wide range of numbers).

Seed: The seed is the starting value of the random number generator. If you keep the seed constant, you will generate the same sequence of numbers each time. You can set the seed manually or dynamically (e.g., based on time) for different results in every run.

LCG Random Function: The function lcg_random() applies the LCG formula to compute the next random number. Each time this function is called, the seed value is updated to the next value in the sequence.

Range Function: random_in_range(min, max) generates a random number within the range [min, max]. The modulus operation ensures that the result fits within the specified range.

Less Use of STL Functions: This implementation doesn't use any STL functions like rand(), srand().I only used time() to explain why I need current time, since current time is also random, and that will produce random sequences of random numbers. Otherwise for a constant seed, the sequence of random number will also be constant though the numbers are random. We rely on the LCG algorithm for generating random numbers.

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
4 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Storm29 (previous revision, new revision, compare).

»
4 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

Hi! I recommend you to paste the code with highlight directly into the post, instead of using screenshots

  • »
    »
    51 minute(s) ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thank you for your suggestion. From next time I will paste codes directly.