How to generate Gaussian pseudo random numbers in c for a given mean and variance?

I have a code here that generates random numbers having an average value of 0f 1 and a std deviation of 0.5. but how do I change this code so that I can generate Gaussian random numbers of any given average and variance?

#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; } 
+6
source share
2 answers

I have a code here that generates random numbers having an average value of 0f 1 and std is 0.5. but how can I change this code so that I can degenerate Gaussian random numbers of any given average and variance?

If x is a random variable from the Gaussian distribution with mean ΞΌ and standard deviation Οƒ , then Ξ±x+Ξ² will have the value Ξ±ΞΌ+Ξ² and standard deviation |Ξ±|Οƒ .

In fact, the code you posted already performs this conversion. It starts with a random variable with a mean of 0 and a standard deviation of 1 (obtained from the random_normal function that implements Box-Muller transform ), and then converts it into a random variable with a mean of 1 and a standard deviation of 0.5 (in the rands array) by multiplying and additions:

 double random_normal(); /* normal distribution, centered on 0, std dev 1 */ rands[i] = 1.0 + 0.5*random_normal(); 
+10
source

There are several ways to do this: all of them basically include converting / displaying your evenly distributed values ​​into a normal / Gaussian distribution. Ziggurat conversion is probably the best choice.

One thing to keep in mind is that the quality of your final distribution is no worse than your RNG, so be sure to use a quality random number generator (e.g. Mersenne twister) if the quality of the generated values ​​is important.

+3
source

Source: https://habr.com/ru/post/894894/


All Articles