# How to generate random boolean values in C++

Generating random Boolean values can be achieved by random number-generating algorithms. These values are used in many probability simulations and cryptography algorithms.

## rand() function:

The rand function is defined in the STL of c++. This function creates pseudo-random numbers. However, the pseudo-random numbers are not always random as they generate the same sequence of numbers every time they run from the start. Therefore, they follow a particular pattern. To resolve this, a function called `srand()`

can be used to seed the pseudo-random number generator algorithm. If we manage to provide a valid random seed a satisfactory randomization could be achieved. Nevertheless, software-based algorithms can never always generate genuine random numbers.

### Providing a seed:

The `srand()`

function accepts a numeric input and the current time of the computer from the epoch can be used as a seed which can almost help to simulate randomization.

The `time()`

function can be used to obtain the current system time. This is the most commonly used approach to provide a random seed. The time function returns an object which can be cast to a numeric type.

## Generate random Boolean value in C++:

When random numbers are generated, the generation of both odd and even numbers is equally likely. Thus if an odd number is generated it can be evaluated as true or false otherwise. The following code illustrates the procedure:

#include <bits/stdc++.h> bool generator() { int g = std::rand(); return (g % 2); // 1 is converted to true and 0 as false } int main() { std::srand(time(0)); bool randomboolean{}; long double tr{};// used to store number of true long double f{};//used to store number of false int n = 5000000; for (int i = 0; i <n ; i++) { randomboolean = generator(); if (randomboolean) { tr++; } else { f++; } } long double pt = tr / n; //probability of true long double pf = f / n;// probability of false std::cout << "probability of true:" << pt << "\n"; std::cout << "probability of false:" << pf << "\n"; }

Here the generator function returns a Boolean value by implicit casting. This function is used to generate 5 million boolean values and the output shows that the generating of both the boolean values is equally likely.

Output: probability of true:0.500016 probability of false:0.499984

#### Conclusion:

Other third-party libraries provide sophisticated algorithms for random number generation algorithms despite the basic principle behind using them being the same as above.

## Leave a Reply