
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Generate random numbers following a normal distribution in C/C++
Here we will see how to generate random numbers, which are following in a normal distribution. For the normal random, the formula is like below.
𝑧 = √−2 ln 𝑥1 cos (2𝜋𝑥2)
Here x1 and x2 are chosen randomly.
Example
#include <cstdlib> #include <cmath> #include <ctime> #include <iostream> using namespace std; double rand_gen() { // return a uniformly distributed random value return ( (double)(rand()) + 1. )/( (double)(RAND_MAX) + 1. ); } double normalRandom() { // return a normally distributed random value double v1=rand_gen(); double v2=rand_gen(); return cos(2*3.14*v2)*sqrt(-2.*log(v1)); } main() { double sigma = 82.0; double Mi = 40.0; for(int i=0;i<20;i++) { double x = normalRandom()*sigma+Mi; cout << " x = " << x << endl; } }
Output
x = 1.91628 x = 57.0448 x = 51.4348 x = 53.5612 x = -83.8511 x = -28.9197 x = -76.0576 x = 62.1435 x = 23.9 x = -87.0663 x = 50.6942 x = 94.1685 x = -88.1597 x = 168.502 x = 40.7563 x = 90.1091 x = 16.9218 x = -36.9178 x = 135.969 x = 56.8888
- Related Articles
- C++ Program to Generate Random Numbers Using Probability Distribution Function
- How to generate standard normal random numbers in R?
- Generate random numbers using C++11 random library
- Generate random numbers in Arduino
- C# program to generate secure random numbers
- How to generate different random numbers in a loop in C++?
- Generate pseudo-random numbers in Python
- Generate Random Integer Numbers in Java
- Generate Random Long type numbers in Java
- Generate random characters and numbers in JavaScript?
- Guide to Generate Random Numbers in Linux
- Java program to generate random numbers
- How does Python generate random numbers?
- How to generate a normal random vector using the mean of a vector in R?
- Excel random data: generate random numbers, texts, dates, times in Excel

Advertisements