C++ Coding - Using NAG for normal
Question Generate pseudo random numbers from the normal distribution with NAG libraries
Given the long winded approach from this postwe are now going to use numerical libraries instead. See the following post (University of Manchester only) for how to set up a visual studio project with NAG libraries:
Once you get up to the stage of adding a new cpp file create a file and add the following code with headers
The extra headers at the top are used to reference specific NAG types (
#include <iostream>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg05.h>
using namespace std;
int main()
{
return 0;
}
nag.h
), NAG's version of stdlib (nag_stdlib.h
), and the g05 chapter of NAG's libraries which is the one that contains random number generators (nagg05.h
). The first 2 libraries must always be included where as the last one depends on what functions we are calling. The particular function we are interested in is the function g05ddc
which accepts two real numbers as arguments (mean and variance) and returns a normally distributed random number (see here for documentation). Then to call the function we can simply write
and to set the seed we must use the function
cout << g05ddc(0.,1.) << endl; // call the random number generator
g05cbc
. You should note that when working with NAG we should use NAG types (Integer
, Nag_Boolean
etc) because different compilers store numbers in different ways. So to generate some normally distributed numbers the code is as follows
#include <iostream>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagg05.h>
using namespace std;
int main()
{
// declare a nag type integer
Integer seed=1;
// set the seed
g05cbc(seed);
// generate some numbers
for(int i=0;i<100;i++)
cout << g05ddc(0.,1.) << endl; // call the random number generator
return 0;
}
Comments
Post a Comment