# 如何获得指定取值范围内符合正态分布的随机值

Sure! The Box-Muller transform is an algorithm that transforms two independent uniformly distributed random variables into two independent normally distributed random variables. Here’s how you can use the Box-Muller transform to generate normally distributed random numbers that are constrained to fall within the range `[a, b]` :

``````#include <iostream>
#include <random>
#include <cmath>

int main()
{
double a = 1.0, b = 10.0; // Define range [a, b]
double c = (a + b) / 2; // Define mean of the normal distribution
double d = 1.0; // Define variance of the normal distribution

// Set up the random number generator and the uniform distribution
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<double> udist(0.0, 1.0);

double random_num;
do {
// Generate two independent uniformly distributed random numbers
double u1 = udist(gen);
double u2 = udist(gen);

// Use the Box-Muller transform to generate two independent normally distributed random numbers
double z1 = std::sqrt(-2.0 * std::log(u1)) * std::cos(2.0 * M_PI * u2);
double z2 = std::sqrt(-2.0 * std::log(u1)) * std::sin(2.0 * M_PI * u2);

// Scale the normally distributed random number to have the desired mean and variance
random_num = c + std::sqrt(d) * z1;

} while (random_num < a || random_num > b); // If the random number is outside the range, keep generating

std::cout << "Random number: " << random_num << std::endl;

return 0;
}
``````

In the above code, we use the Box-Muller transform to generate two independent normally distributed random numbers, z1 and z2, that have a mean of 0 and a variance of 1. We then scale z1 to have the desired mean and variance by multiplying it by the standard deviation (std::sqrt(d)) and adding the mean (c). We also use a do-while loop to generate random numbers until a number is generated that falls within the specified range [a, b].