Chcę wylosować liczby korzystając z rozkładu normalnego gaussa. Liczby maja byc z przedzialu [0,x] gdzie x ustalam sobie w programie.
napisałem sobie już kod, ale nie działa poprawnie, tzn. losowane liczby nie sa z przedzialu [0,x] ...
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <time.h>
using namespace std;
#define PI 3.14159265
double randn(double mu, const double sigma)
{
const double gap = 0.01;
const int length = (int)(2*sigma*6/gap);
double *X = new double[length];
double *P = new double[length];
X[0] = -sigma*6+mu;
for (int k=1; k<length; k++)
X[k] = X[k-1] + gap;
P[0] = 0.0;
for (int k=1; k<length;k++)
P[k] = P[k-1] + exp(-((X[k]-mu)*(X[k]-mu))/(2*sigma*sigma))/(sqrt(2*PI)*sigma);
for (int k=0; k<length; k++)
P[k] = P[k]/P[length-1];
double temp_rand = (double)rand()/RAND_MAX;
int i;
for(i=0; i<length;i++)
{
if(P[i]>temp_rand)
break;
}
return X[i-1] + (X[i]-X[i-1])*(temp_rand-P[i-1])/(P[i]-P[i-1]);
}
int main()
{
srand((unsigned)time(0));
for(int i=1; i<100; i++)
{
cout<<randn(0, 10) << endl;
}
return 0;
}