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?
#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;
}
Use the formula "=NORMINV(RAND(),B2,C2)", where the RAND() function creates your probability, B2 provides your mean and C2 references your standard deviation. You can change B2 and C2 to reference different cells or enter the values into the formula itself.
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?
If x
is a random variable from a Gaussian distribution with mean μ
and standard deviation σ
, then αx+β
will have mean αμ+β
and standard deviation |α|σ
.
In fact, the code you posted already does this transformation. It starts with a random variable with mean 0 and standard deviation 1 (obtained from the function random_normal
, which implements the Box–Muller transform), and then transforms it to a random variable with mean 1 and standard deviation 0.5 (in the rands
array) via multiplication and addition:
double random_normal(); /* normal distribution, centered on 0, std dev 1 */
rands[i] = 1.0 + 0.5*random_normal();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With