C programming
random numbers
code example
number generation
C language

Generating random number between -1, 1 in C?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Generating random numbers is a fundamental task in programming, utilized in various applications ranging from simple simulations to complex cryptographic systems. In the C programming language, generating random numbers within a specific range, such as between `-1` and `1`, can be achieved using a combination of C library functions. This article will take you through the necessary steps to accomplish this, offering both theoretical insights and practical examples.

Random Number Generation in C

C provides a standard library function `rand()` from `stdlib.h` to generate pseudo-random numbers. The `rand()` function returns an integer ranging from `0` to `RAND_MAX`, where `RAND_MAX` is a constant defined in the same library. To generate numbers within a specific range, additional computations are needed.

Generating Random Floats in Range [1,1][-1, 1]

To generate random floating-point numbers between 1-1 and 11, follow these steps:

  1. Normalization: Scale the integer result of `rand()` to a floating-point number in the range [0,1][0, 1].
  2. Transformation: Transform the normalized value to the desired range.

Here’s how it can be done:

  • Seeding with `srand()`: The `srand()` function seeds the random number generator used by `rand()`. In the example above, it's seeded with the current time using `time(NULL)`, which ensures different sequences of random numbers on different program executions.
  • Normalization and Scale Transformation:
    • The formula `rand() / (float) RAND_MAX` normalizes the integer output to a float in the range [0,1][0, 1].
    • Scaling with `2.0f` and subtracting by `1.0f` shifts and scales the range to [1,1][-1, 1].
  • Determinism: Without seeding, the `rand()` function will generate the same sequence of pseudo-random numbers on every execution, which may not be desirable in many applications.
  • Quality: The standard `rand()` function provides a basic uniform distribution, not suitable for high-security applications. For cryptographic purposes, use more robust libraries like OpenSSL or specialized system calls.
  • Repeatability: For simulations requiring reproducibility, choose an initial seed and document it to regenerate the same sequence of pseudo-random numbers.

Course illustration
Course illustration

All Rights Reserved.