Generate Random Numbers Using Probability Distribution Function in C++



The probability density function (pdf) is a function that describes the relative likelihood for this random variable to take on a given value. It is also called as density of a continuous random variable.

The probability of the random variable fall within a particular range of values is given by the integral of this variable's density over that range, So, it is given by the area under the density function but above the horizontal axis and between the lowest and greatest values of the range. Probability Distribution is based upon this probability density function.

In this article, we will generate random numbers based on a custom probability density function in C++. The function will generate numbers 1, 2, and 3 with probabilities of 50%, 30%, and 20% respectively.

Steps using Probability Distribution Function

To generate random numbers using probability distribution function in C++, we will follow below mentioned steps:

  • The randomPdf() function generates random numbers using ana custom probability distribution function.
  • This function uses a simple logic where a random number is generated between 1 and 100 and stored in the variable r.
  • If r is less than or equal to 50, the function returns 1. Similarly, it returns 2 if r is between 51 and 80 and returns 3 if r lies between 81 and 100.
  • In the main() function, srand(time(nullptr)) seeds the current time to generate different random numbers on each run.
  • A for loop calls randomPdf() function repeatedly to generate and print 5 random values that is set by sampleSize.

Random Number Generator using PDF in C++

Below is the C++ code to generate random numbers using a custom probability distribution function:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int randomPdf() {
    int r = rand() % 100 + 1; // Random number between 1 and 100
    if (r <= 50)
        return 1; // 50% chance
    else if (r <= 80)
        return 2; // 30% chance (51 to 80)
    else
        return 3; // 20% chance (81 to 100)
}

int main() {
    srand(time(nullptr)); // Seed the random number generator
    const int sampleSize = 5;
    cout << "Generated random numbers:\n";
    for (int i = 0; i < sampleSize; ++i) {
        cout << randomPdf() << " ";
    }
    cout << endl;
    return 0;
}

The output of the above code is:

Generated random numbers:
2 2 3 2 1 
Updated on: 2025-04-22T11:38:55+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements