9/29/03
1) Invoke the random generator. Start an accumulator variable at 0 and an index at e(1). Increment the index through the e(i)'s and add p(i) to the variable. When the accumulator exceeds the random number, return e(i-1).
2) Run the previous algorithm as if the random number were 1, storing the intermediate values of the accumulator (distribution function) in a sorted container. When the new algorithm is called, search the container for the greatest value less than a random number and return its index.
3)
#include<iostream>
using namespace std;
#include "stdlib.h"
#include "time.h"
const int uniformSamples = 100;
double getNormalVal(double mean, double stddev)
{
// Central Limit Theorem:
// The sum of N random #'s between 0 and 1 is normal @ N/2
double randVal = 0;
for (int i=0; i < uniformSamples; ++i)
{
randVal += rand() / double(RAND_MAX+1);
}
// Center around 0
randVal -= uniformSamples / 2.;
// Scale by std dev
randVal *= stddev * 12./uniformSamples;
// Shift to mean
randVal += mean;
return randVal;
}
int main(int argc, char ** argv)
{
if (argc != 4)
{
cerr << "NormalSample mean stddev vals" << endl;
return -1;
}
srand( time(NULL) );
double mean = strtod(argv[1], NULL);
double stddev = strtod(argv[2], NULL);
int vals = atoi(argv[3]);
for (int i=0; i < vals; ++i)
{
cout << getNormalVal(mean, stddev) << endl;
}
return 0;
}
Back to
MachineLearning
There are no comments on this page. [Add comment]