Random库–正态分布
背景介绍
正态分布(Normal distribution)又名高斯分布(Gaussian distribution),是一个在数学、物理及工程等领域都非常重要的概率分布,在统计学的许多方面有着重大的影响力。若随机变量X服从一个数学期望为μ、方差为σ^2 的高斯分布,记为N(μ,σ^2 )。其概率密度函数为正态分布的期望值μ决定了其位置,其标准差σ决定了分布的幅度。因其曲线呈钟形,因此人们又经常称之为钟形曲线。我们通常所说的标准正态分布是μ = 0,σ = 1的正态分布。
Normal distribution
Random number distribution that produces floating-point values according to a normal distribution, which is described by the following probability density function:
This distribution produces random numbers around the distribution mean (μ) with a specific standard deviation (σ).
The normal distribution is a common distribution used for many kind of processes, since it is the distribution that the aggregation of a large number of independent random variables approximates to, when all follow the same distribution (no matter which distribution).
The distribution parameters, mean (μ) and stddev (σ), are set on construction.
To produce a random value following this distribution, call its member function operator().
实现要求
———- adaptor ———-
about: normalize the random numbers to [0, 1].
adaptor() // default constructor
double min() const // return the minimun that the adaptor
// can express.
double max() const // return the maximun that the adaptor
// can express.
double operator()() // normalize the random numbers to [0, 1].
Tips(pseudo code):
remember, you need to realize adaptor as the following way!
# b = the digits of numeric_limits<double>
# r = generator.max - generator.min + 1
# log2r = log(r) / log(2)
# k = max(1, (b + log2r - 1) / log2r)
# sum = 0 and tmp = 1
# loop k -> 0
# sum += (generator.randomNumber - generator.min) * tmp
# tmp = tmp * r
# end loop
# return sum / tmp
———- normal_distribution_my ———-
about: adapt the random number with adaptor and simulate
the normal distribution.
double mean, stddev; // two parameter: mean and standard deviation.
adaptor aurng; // adaptor to normalize the random number
normal_distribution_my(); // default constructor, mean = 0, stddev = 1.
double min() const; // return the minimun real number it can express.
double max() const; // return the maximun real number it can express.
double operator()(); // use its adaptor to simulate normal distribution.
Tips(pseudo code):
remember, you need to realize normal_distribution as the following way!
# loop until r2 -> (0, 1]
# x = 2 * adaptor - 1
# y = 2 * adaptor - 1
# r2 = x * x + y * y
# end loop
# mult = sqrt(-2 * log(r2) / r2)
# ret = y * mult
# ret = ret * standard deviation + mean
# return ret
代码实现
测试文件