Welcome to our deep dive into the world of C++'s std::normal_distribution! In this tutorial, we'll learn how to generate random numbers following a normal (Gaussian) distribution, making our programs more robust and realistic.
š” Pro Tip: Understanding normal distribution is crucial for many applications like simulations, data analysis, and machine learning. Let's get started!
std::normal_distribution is a C++ library function that generates random numbers following a normal distribution, also known as the bell curve or Gaussian distribution.
#include <iostream>
#include <random>
#include <numeric>
int main() {
// Create a normal distribution instance with mean 0 and standard deviation 1
std::normal_distribution<double> dist(0, 1);
// Generate 10 random numbers
std::vector<double> numbers(10);
std::generate_n(numbers.begin(), numbers.size(), dist);
// Print the generated numbers
std::cout << "Generated numbers:\n";
for (const auto& number : numbers) {
std::cout << number << "\n";
}
return 0;
}š Note: The above code creates a std::normal_distribution object with a mean (average) of 0 and a standard deviation of 1. It generates 10 random numbers and prints them out.
The std::normal_distribution constructor takes two parameters:
mean: The average value of the distribution.stddev: The standard deviation (spread) of the distribution.You can adjust these parameters to generate random numbers with different means and standard deviations.
Let's create a simple weather simulation where we generate daily temperature readings. We'll use a normal distribution to make the simulation more realistic.
#include <iostream>
#include <random>
#include <vector>
int main() {
// Create a normal distribution for daily temperature readings
std::normal_distribution<double> tempDist(20, 5);
// Generate temperatures for 30 days
std::vector<double> temperatures(30);
std::generate_n(temperatures.begin(), temperatures.size(), tempDist);
// Print the generated temperatures
std::cout << "Generated temperatures:\n";
for (const auto& temperature : temperatures) {
std::cout << temperature << "\n";
}
return 0;
}š Note: The above code creates a std::normal_distribution object for daily temperature readings with a mean of 20°C and a standard deviation of 5°C. It generates 30 random temperatures and prints them out.
What does `std::normal_distribution` help us achieve in C++?
Remember, practice makes perfect! Keep coding and exploring the fascinating world of C++. Happy learning! š”šš