Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate gaussian pseudo random numbers in c for a given mean and variance?

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;

}
like image 708
Divya Avatar asked Aug 12 '11 02:08

Divya


People also ask

How do you generate random numbers with mean and standard deviation?

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.


1 Answers

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();
like image 84
nibot Avatar answered Sep 30 '22 13:09

nibot