Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

My program is the monte carlo integration of a square from 0 to 1 on both axis.

ID: 3534423 • Letter: M

Question

My program is the monte carlo integration of a square from 0 to 1 on both axis. It is suppose to output the area and error from the true value for sets of 1000, 10000, and 100000 sets of random numbers. I do not know if my cout for area or error is right. Help. My function is sin(x). So far I have:

#include <iostream><?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

#include <cmath>

#include <cstdlib>

using namespace std;

double MonteCarlo(double x)

{

       return (sin(x));

}

int main()

{

       double count, limit, rand_x, rand_y, k, i;

       rand_x = double(rand())/RAND_MAX;

       rand_y = double(rand())/RAND_MAX;

      

       limit = 100;

       for(i=0; i<3 ; ++i)

       {

             limit*= 10;

             count = 0;

             for(k=0; k<limit; k++)

             {

                    if(rand_y <= MonteCarlo(rand_x))

                    count++;

             }

     cout<< "The area of the function is: " << /*???????*/ (count/limit) << " while the percent error is: " << /*??????*/(count/.4596976941) << " ";

       }

       return 0;

}

Explanation / Answer

Remember not to rely on rand() or random() family of functions in C, as they are linear congruential pseudorandom number generators (Wikipedia), and are likely to introduce artefacts/errors when used in Monte Carlo stuff. I warmly recommend using Xorshift instead. In particular:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 #include <stdint.h> static uint32_t prng_state[4] = {         123456789U,         362436069U,         521288629U,         88675123U }; static inline uint32_t prng_u32(void) {         uint32_t        temp;         temp = prng_state[0] ^ (prng_state[0] << 11U);         prng_state[0] = prng_state[1];         prng_state[1] = prng_state[2];         prng_state[2] = prng_state[3];         return prng_state[3] ^= (temp >> 8U) ^ temp ^ (prng_state[3] >> 19U); } /* 0.0 <= prng_one() < 1.0 */ static inline double prng_one(void) {         return (double)prng_u32() / 18446744073709551616.0              + (double)prng_u32() / 4294967296.0; }
Dr Jack
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote