Sunday, June 20, 2010

boost library- C++

Link to boost library header file in glacier.westgrid.ca

g++ -I/global/software/boost-1.33_1 example.cpp

Boost library provide different random number generators.

Example using lagged_fibonacci607 and uniform distribution to calculate pi:

(This blog has difficulty to post C++ code. I need online
cpp2html converter )


-------------------------------------------------------------------------------------
#include <boost/random.hpp>
#include <iostream>
#include <boost/limits.hpp>
#include <ctime>                  
using namespace std;
using namespace boost;



int main()
{
// A. Define the lagged Fibonacci and Uniform objects
lagged_fibonacci607 rng;
rng.seed(static_cast<uint32_t> (std::time(0)));

uniform_real<> uni(0.0,1.0);

// B. Produce Uniform (0, 1)
variate_generator<lagged_fibonacci607&, uniform_real<> >uniRng(rng, uni);

// C. Choose the desired accuracy
cout << "How many darts to throw? "; long N; cin >> N;

// D. Thow the dart; does it fall in the circle or outside
// Start throwing darts and count where they land
long hits = 0;
double x, y, distance;

for (long n = 1; n <= N; ++n)
{

x = uniRng(); y = uniRng();
distance = sqrt(x*x + y*y);

if ( distance <=1)
{
hits++;
}
}

// E. Produce the answer
cout << "PI is: " << hits << ", " << 4.0 * double(hits) / double (N);

return 0;

}
------------------------------------------------------------
Using normal distribution to calculate pi


#include <boost/random.hpp>     // Convenience header file

#include <iostream>
#include <ctime>                        // std::time
#include <boost/limits.hpp>
using namespace std;
using namespace boost;

int main()
{

normal_distribution<> nor(0,1);
lagged_fibonacci607 rng;

rng.seed(static_cast<uint32_t> (std::time(0)));
// Produce Normal (0, 1)
variate_generator<lagged_fibonacci607&, normal_distribution<> > norRng(rng, nor);

cout << "How many darts to throw? "; long N; cin >> N;

double a, b, c, factor;
long hits = 0;

// The dart board
for (long n = 1; n <= N; ++n)
{

// Generate 3 N(0,1) variates
a = norRng(); b = norRng(); c = norRng();

factor = b*b - 4.0*a*c;

if ( factor >= 0.0)
{
hits++;
}
}
cout << "Prob of positive roots: " << hits << ", " << double(hits) / double (N);

return 0;

}
~

1 comment: