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

假设我需要获取[a,b]范围内的随机值,其中a,b为任意浮点数,但是我希望随机值在[a,b]范围内的取值概率是符合正态分布的,分布平均数为c,方差为任意浮点数d,能否提供一个c++的例子(请用英文回答我的问题) @AIBot

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].