Generate Truly Random Numbers in C: A Complete Guide to rand() & srand()

1. How to Generate Random Numbers in C: The `rand()` Function

1.1 What is the `rand()` Function?

The rand() function in C is used to generate pseudo-random numbers. Pseudo-random numbers are sequences generated by a predetermined algorithm, and while not truly random, they are sufficient for most general purposes. rand() returns an integer in the range of 0 to 32767. This range might vary by system, but this is the common value.

1.2 Basic Usage of the `rand()` Function

To use the rand() function, you need to include stdlib.h. The following code is a basic example of generating a random number using rand().

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

int main(void) {
    int randomNumber = rand(); 
    printf("Generated random number: %d\n", randomNumber);
    return 0;
}

Running this code will display a random number between 0 and 32767. However, a drawback is that the same random number will be generated every time. We will discuss this further later.

2. Adjusting the Range of Random Numbers

2.1 Limiting the Range Using the Modulo Operator

When generating random numbers, you often need values within a specific range. For example, to generate a random number from 1 to 100, you can adjust the output of the rand() function using the modulo operator %.

int numberInRange = rand() % 100 + 1; // Generates a random number from 1 to 100

In this example, we get the remainder of rand()‘s output divided by 100, and then add 1 to generate a random number from 1 to 100. Using the modulo operator makes it easy to generate random numbers within any desired range.

2.2 Generating Range-Specific Random Numbers

For more flexible control over the random number range, you can create and use a custom function. Below is an example of a function that generates a random number within a specified minimum and maximum range.

int getRandomNumber(int min, int max) {
    return rand() % (max - min + 1) + min;
}

Using this function, you can generate random numbers within any range, such as getRandomNumber(1, 100).

侍エンジニア塾

3. Changing Random Number Patterns with `srand()`

3.1 What is the `srand()` Function?

If you use the rand() function as is, the same random number pattern will be generated every time the program runs. This is a characteristic of pseudo-random numbers, which is convenient for debugging but problematic when practical randomness is required. To address this, you can use the srand() function to set the random number seed, thereby changing the pattern of generated random numbers.

3.2 How to Use the `srand()` Function

The srand() function is called before rand() to specify the random number seed. Typically, srand((unsigned int)time(NULL)) is used to set the current time as the seed.

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

int main(void) {
    srand((unsigned int)time(NULL)); // Set current time as seed
    int randomNumber = rand(); 
    printf("Generated random number: %d\n", randomNumber);
    return 0;
}

In this code, srand() generates a different random number pattern each time. Since time(NULL) returns the current time in seconds, it’s possible to set a different seed every time.

4. Practical Applications of Random Numbers

4.1 Using Random Numbers in Games

Random numbers are frequently used in game development. For example, they are used to randomly set character positions or determine item drop probabilities. Below is an example of a dice roll simulation.

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

int main(void) {
    srand((unsigned int)time(NULL)); // Set the seed
    int diceRoll = rand() % 6 + 1; // Generate a random number from 1 to 6
    printf("Dice roll: %d\n", diceRoll);
    return 0;
}

This program generates a random number from 1 to 6, outputting it as a dice roll. By using random numbers, you can easily implement unpredictable elements in games.

4.2 Monte Carlo Simulation

Random numbers are also used in simulations like the Monte Carlo method. The Monte Carlo method uses random numbers to approximate solutions to problems that are difficult to solve analytically. For example, you can approximate the value of Pi (π) using random numbers.

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

int main(void) {
    int n_trials = 1000000;
    int n_inside = 0;
    double x, y, pi;

    srand((unsigned int)time(NULL));

    for (int i = 0; i < n_trials; i++) {
        x = (double)rand() / RAND_MAX;
        y = (double)rand() / RAND_MAX;
        if (x * x + y * y <= 1) {
            n_inside++;
        }
    }

    pi = 4.0 * n_inside / n_trials;
    printf("Approximated π: %f\n", pi);

    return 0;
}

This program is an example of the Monte Carlo method approximating Pi using random points. It uses rand() to generate random numbers in the range of 0 to 1, and then uses them to approximate the area of a circle.

5. Important Considerations for `rand()` and `srand()`

5.1 Understanding Pseudo-randomness

The random numbers generated by C's rand() function are pseudo-random. They are not truly random values but are calculated based on an internal algorithm, meaning that using the same seed will produce the same random number pattern. While this is useful for debugging, it is not suitable when true randomness is required.

5.2 Common Mistakes

Common mistakes when using random numbers include not using srand() or misunderstanding the output range of rand(). Specifically, if you don't set a seed with srand() before using rand(), the same pattern of random numbers will be generated every time. Also, when adjusting the range with rand() % n, be careful as the value of n can lead to unintended results.

Conclusion

Generating random numbers in C is utilized in various fields, such as games and simulations. By understanding how to use the rand() and srand() functions and properly generating random numbers, you can add unpredictable elements to your programs. Refer to this article and try creating programs that utilize random numbers.

侍エンジニア塾