我这里有一个代码,它产生的平均0f 1和std偏差为0.5的随机数.但是我如何修改这个代码,以便我能够确定任何给定均值和方差的高斯随机数?
- #include <stdlib.h>
- #include <math.h>
- #ifndef M_PI
- #define M_PI 3.14159265358979323846
- #endif
- double drand() /* uniform distribution,(0..1] */
- {
- return (rand()+1.0)/(RAND_MAX+1.0);
- }
- double random_normal()
- /* normal distribution,centered on 0,std dev 1 */
- {
- return sqrt(-2*log(drand())) * cos(2*M_PI*drand());
- }
- int main()
- {
- int i;
- double rands[1000];
- for (i=0; i<1000; i++)
- rands[i] = 1.0 + 0.5*random_normal();
- return 0;
- }
解决方法
I have a code here which generates random numbers having a mean 0f 1
and std deviation of 0.5. but how do i modify this code so that i can
denerate gaussian random numbers of any given mean and variance?
如果x是来自具有平均μ和标准偏差σ的高斯分布的随机变量,则αxβ将具有平均αμβ和标准偏差|α|σ.
实际上,您发布的代码已经进行了这种转换.它以随机变量开始,均值为0,标准差为1(从函数random_normal获得,实现Box–Muller transform),然后通过乘法将其转换为均值为1且标准差为0.5(在rands数组中)的随机变量加成:
- double random_normal(); /* normal distribution,std dev 1 */
- rands[i] = 1.0 + 0.5*random_normal();