Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <math.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <vector>
- using namespace std;
- struct Ran {
- /*
- Implementation of the highest quality recommended generator. The constructor is called with
- an integer seed and creates an instance of the generator. The member functions int64, doub,
- and int32 return the next values in the random sequence, as a variable type indicated by
- their names. The period of the generator is roughly 3.138 x 10^57.
- */
- unsigned long u,v,w;
- Ran(unsigned long j) : v(4101842887655102017LL), w(1) {
- // Constructor. Call with any integer seed (except value of v above).
- u = j ^ v; int64();
- v = u; int64();
- w = v; int64();
- }
- inline unsigned long int64() {
- // Return 64-bit random integer.
- u = u * 2862933555777941757LL + 7046029254386353087LL;
- v ^= v >> 17; v ^= v << 31; v ^= v >> 8;
- w = 4294957665U*(w & 0xffffffff) + (w >> 32);
- unsigned long x = u ^ (u << 21); x ^= x >> 35; x ^= x << 4;
- return (x + v) ^ w;
- }
- inline double doub() { return 5.42101086242752217E-20 * int64(); }
- // Return random double-precision floating value in the range 0. to 1.
- inline unsigned int int32() { return (unsigned int)int64(); }
- // Return 32-bit random integer.
- };
- //int count;
- double total, inBox;
- // user defined function below
- double f (double x){
- return exp(cos(x));
- }
- //
- //function to calculate a definite integral given bounds of integration (xmin/max) & bounds of function (ymin/ymax)
- double integral (double (*f)(double), double xmin, double xmax, double ymin, double ymax,int n){
- for (int count=0; count < n; count++){
- double u1 = rndvar.int64();
- double u2 = rndvar.int64();
- double xcoord = ((xmax - xmin)*u1) + xmin;
- double ycoord = ((ymax - ymin)*u2) + ymin;
- double val = f(xcoord);
- total++;
- if (val > ycoord){
- inBox++;
- }
- }
- double density = inBox/total;
- std::cout<<(xmax - xmin)*(ymax - ymin)*density<<std::endl;
- }
- int main (int argc, char **argv)
- {
- if(argc != 3) {
- printf("Need 2 arguments: seed n\n");
- exit(0);
- }
- unsigned long iseed=atol(argv[1]);
- int n=atoi(argv[2]); // number of steps
- vector <int> test;
- Ran rndvar(iseed);
- cout<< "RESULT: " <<endl;
- integral(f,-2,2,0,4,n);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement