# 2-d monte carlo integration help

Show 80 post(s) from this thread on one page
Page 3 of 5 First 12345 Last
• 10-01-2012
jsuite
Quote:

Actually, I was wondering if "tester" was BOTH a function, AND sometimes referred to the program "testing" in the simulation. It is confusing.

This is just the Pythagorean theorem:
RETURN 1 if sqrt(x*x + y*y) <= r, ELSE 0

Where x = A, y = B, and r = C˛ in A˛ + B˛ = C˛

So to tell if it's inside the circle, get the x and y point of the hit, and the x and y values of the center of the circle. Then:

We get a triangle from the hit, to the center of the circle:

X -x == base distance of the triangle
Y - y == height distance of the triangle

Now base˛ + height˛ == hypotenuse˛ (distance as the crow flies), from the hit, to the center of the circle.

If hypotenuse is greater than the radius of the circle, then it's outside the circle. If it's less than or equal to, it's inside the circle.

For instance, if the triangle had base of 3, and height of 4, then the hypotenuse would be 5, since:
3˛ + 4˛ = 5˛

So if the radius of the circle was > 5, the hit would be outside the circle. If it's less than or equal to 5, then it's inside it.

Ok, i think the function for DartHits works as is. Current code:

Code:

```#include <stdio.h> #define PI 3.14159 #define RADIUS 10 double RandNumInRange (double, double); int main (void) {   int k;   printf("Please enter a seed");   scanf(%d, k);   srand(k); } void GetBorders(double *xmin, double *xmax, double *ymin, double *ymax) {   double a, b, c, d;   a = 27;   b = 57;   c = 33;   d = 63;   *xmin = a;   *xmax = b;   *ymin = c;   *ymax = d; } double RandNumInRange (double z, double w) //where w is any max value, and z is any min value {   double rn;   int i = 0;   srand(1);   while (i<1)   {     i++;     rn = ((double)rand()/(double)RAND_MAX)*(w-z);   } return rn; } DartHits(double a, double b) {   double distance = sqrt(a*a + b*b);   if (distance <= RADIUS)   {     return 1;   }   else   {     return 0;   } } double ThrowDarts() {   double n;   printf("How many darts would you like to throw?");   scanf("&d", &llu);   double xmax, xmin, ymax, ymin;   GetBorders(&xmin, &xmax, &ymin, &ymax);   double rectArea = (xmax -xmin) * (ymax - ymin);   double xdart;   double ydart;   int i = 1; //loop goes here: while (i <= n)   {     double nhit;     xdart = rand(xmin,xmax); //generate random number between xmin and xmax       xdart = RandNumInRange(xmin,xmax);         ydart = rand(ymin,ymax); //generate random number between ymin and ymax       ydart = RandNumInRange(ymin,ymax);     nhit = DartHits(xdart,ydart);       if (nhit != 0)         nhit++;   }   double estRectArea = rectArea * (nhit/n);   return estRectArea; }```
Questions: How's everything look so far (is DartHits proper?) (minus formatting)
Rand still isn't working properly, and seed is entered by the user. Can srand be in main()? How do I pass N (number of hits, entered by user) to the ThrowDarts function?

P.S. are you available to use any form of Instant messenger? Trying to finish this tonight. If not I completely understand, do not want to be pressing in the least.
• 10-01-2012
jsuite
Ok disregard last post, most updated code with new questions:

Code:

```#include <stdio.h> #include <stdlib.h> #include <math.h> #define PI 3.14159 #define RADIUS 10 double RandNumInRange (double, double); double DartHits(double, double); double ThrowDarts(); int main (void) { } void GetBorders(double *xmin, double *xmax, double *ymin, double *ymax) {   double a, b, c, d;   a = 27;   b = 57;   c = 33;   d = 63;   *xmin = a;   *xmax = b;   *ymin = c;   *ymax = d; } double RandNumInRange (double z, double w) //where w is any max value, and z is any min value {   double rn;     srand(1);   rn = ((double)rand()/(double)RAND_MAX)*(w-z); return rn; } double DartHits(double a, double b) {   double distance = sqrt(a*a + b*b);   if (distance <= RADIUS)   {     return 1;   }   else   {     return 0;   } } double ThrowDarts(double estRectArea) {   double n = 100;   double xmax, xmin, ymax, ymin;   GetBorders(&xmin, &xmax, &ymin, &ymax);   double rectArea = (xmax -xmin) * (ymax - ymin);   double xdart;   double ydart;   int i = 1;   double nhit; //loop goes here: while (i <= n)   {     //generate random number between xmin and xmax       xdart = RandNumInRange(xmin,xmax);       //generate random number between ymin and ymax       ydart = RandNumInRange(ymin,ymax);     nhit = DartHits(xdart,ydart);       if (nhit != 0)       {         nhit++;       }   }   estRectArea = rectArea * (nhit/n);   return estRectArea; }```
Things left to do: scanf seed number, pass it to rand, and make rand work.
pass n amount of hits to ThrowDarts function (pointers? if so, example?)
finally put it together and make the printout statements and properly format.

I'm am unsure how to do these things, but after this I'll be finished :D
It's due in ~18hrs from now. Thanks for all the help thus far, it's really helped a lot.

p.s nhits is a set number for now, until i figure out how to read it in and pass it to the ThrowDarts() function
• 10-01-2012
srand should go out of your random function. high up in main would be good for it, because you only want to call it ONCE, and it must be early to be of any use. The scanf() for it, can be done right there.

int seed;

scanf("%d",&seed) and then srand(seed), should work OK. Rand doesn't need your seed number, unless your assignment requires it to be there. srand() works before rand, and "behind the scene", from rand.

Code:

```#include <stdio.h> #include <stdlib.h> void getRandom(int mini,int maxi,int *rnumi, double min,double max,double *rnum, int type); int main(void) {   double xmin, xmax, ymin, ymax,rnum;   int i, rnumi,xmini,xmaxi;   srand(1);   getRandom(0, 25,&rnumi,xmin,xmax,&rnum, 2);   printf("\n");   return 0; } void getRandom(int mini,int maxi,int *rnumi, double min,double max,double *rnum, int type) {   int i;     for(i=0,maxi=30;i<300;i++) {       if(!type) { //get random ints         *rnumi=rand() % maxi + mini+1;  //ints: range is mini - maxi         printf("%5.2d  ",*rnumi);       }       else if(type==1) {         *rnum = (double) (rand() % (int) (max +1)); //doubles: range is 1 - max, .00 numbers only            printf("%5.2f  ",*rnum);       }       else if(type==2) {         *rnum = (double) rand()/(double) RAND_MAX; //doubles: range is 0 - 1. non-integral doubles (0.53,0.11, type numbers)         printf("%5.2f  ",*rnum);       }               }     printf("\n");   } This allows both ints and doubles to be set to a random value, with the data type and range being determined by the "type" variable. Only the rnumi (a rnum integer) or rnum (a double), is passed with a pointer (address only). I'll look at the rest of it, in a couple hours. You have been busy! ;)```
• 10-01-2012
This is your program with a few tweaks. I haven't run it, but it (still) compiles.

Ask away if you have any questions or problems.

Code:

```#include <stdio.h> #include <stdlib.h> #include <math.h> #define PI 3.14159 #define RADIUS 10         double RandNumInRange (double, double); int DartHits(double, double); double ThrowDarts(unsigned long *, double *, double *, double *, double *); void analysis(double,unsigned long,double,double,double,double,double,   double,double,double,unsigned long);         int main (void) {   int seed;   unsigned long N; //number of darts to be thrown   double estRectArea;   double lowx, lowy, hix, hiy;      printf("Enter the integer for the seed: ");   scanf("%d",&seed);   srand(seed);        estRectArea = ThrowDarts(&N,&lowx,&lowy,&hix,&hiy);    printf("\n");   return 0; } void GetBorders(double *xmin, double *xmax, double *ymin, double *ymax) {   double a, b, c, d;       a = 27;   b = 58;   c = 3;   d = 34;       *xmin = a;   *xmax = b;   *ymin = c;   *ymax = d; } double RandNumInRange (double z, double w) { //where w is any max value, and z is any min value   double rn;         rn = ((double)rand()/(double)RAND_MAX)*(w-z);       return rn; }   int DartHits(double x, double y) {   double distance = sqrt(x*x + y*y);       if (distance <= RADIUS) {       return 1;   }   else {       return 0;   } } double ThrowDarts(unsigned long *N,double *lowx,double *lowy,double *hix,double *hiy) {     printf("Enter the number of darts to be thrown in this simulation: ");   scanf("%ul",N);     double xmax, xmin, ymax, ymin;   GetBorders(&xmin, &xmax, &ymin, &ymax);   double rectArea = (xmax -xmin) * (ymax - ymin);   double estRectArea = 0.0;    double xdart;   double ydart;   int i = 1;   unsigned long nhit = 0; //hits can't be anything but integers           //loop goes here:   lowx=lowy=0;   hix=hiy=0;   while (i <= *N) {       //generate random number between xmin and xmax       xdart = RandNumInRange(xmin,xmax);       if(xdart<*lowx)         *lowx=xdart;       if(xdart>*hix)         *hix=xdart;        //generate random number between ymin and ymax       ydart = RandNumInRange(ymin,ymax);       if(ydart<*lowy)         *lowy=ydart;       if(ydart>*hiy)         *hiy=ydart;       if(DartHits(xdart,ydart)) {         nhit++;       }   }   estRectArea = rectArea * (nhit/ *N);   return estRectArea;      } void analysis(double estRectArea, unsigned long N, double xmin,double xmax,double ymin,double ymax,   double lowx,double lowy,double hix, double hiy, unsigned long nhits) {    double percentError = 0.0   double error = 0;   double actualArea = (ymax-ymin) * (xmax-xmin);     printf("Rectange has length of %f and a width of %f\n",ymax-ymin,xmax-xmin);   printf("Area of the rectangle is: %f\n",actualArea);   printf("Darts thrown: %lu. Hits: %ul, hit percentage: %f%\n\n",N,nhits,(double)(nhits/N)*100);     error = abs(actualArea - estRectArea);   printf("Estimated Rectangular Area: %f Error in Area: %f\n",estRectArea,error);     percentError = (error/actualArea) * 100;   printf("Percent error was: %f%\n",percentError);  } /*  What Analysis function should do: 1. Length and width of enclosing rectangle 2. Area of enclosing rectangle 3. Number of darts thrown 4. How many darts hit the shape 5. Percentage of darts that hit the shape 6. Area of the shape computed by out dart throwing 7. Actual area of shape as known from an equation 8. The absolute value difference between these quantities (i.e., the error) */```
• 10-01-2012
jsuite
well, getting segmentation fault errors. Even went to the cs tutor in which they couldn't help me. Spent 25+ hours on this. Really dissapointed. Heres my current code, somethigns wrong with n being a ul and then being used by a formula that wants a answer as a double. Also yhi, ylow, etc.. not sure if they even have values...

code:

Code:

``` #include <stdio.h>#include <stdlib.h> #include <math.h> #define PI 3.14159 #define RADIUS 10 double RandNumInRange (double, double); int DartHits(double, double); double ThrowDarts(unsigned long *, double *, double *, double *, double *); void analysis(double estRectArea, unsigned long N, double xmin, double xmax, double ymin, double ymax,   double lowx, double lowy, double hix, double hiy, double nhits); int main (void) {   int seed;   unsigned long N; //number of darts to be thrown   double estRectArea;   double lowx, lowy, hix, hiy;    printf("Enter the integer for the seed: ");   scanf("%d",&seed);   srand(seed);      estRectArea = ThrowDarts(&N,&lowx,&lowy,&hix,&hiy);    printf("\n");   return 0; } void GetBorders(double *xmin, double *xmax, double *ymin, double *ymax) {   double a, b, c, d;   a = 27;   b = 58;   c = 3;   d = 34;   *xmin = a;   *xmax = b;   *ymin = c;   *ymax = d; } double RandNumInRange (double z, double w) { //where w is any max value, and z is any min value   double rn;   rn = ((double)rand()/(double)RAND_MAX)*(w-z);   return rn; } int DartHits(double x, double y) {   double distance = sqrt(x*x + y*y);   if (distance <= RADIUS) {       return 1;   }   else {       return 0;   } } double ThrowDarts(unsigned long *N,double *lowx,double *lowy,double *hix,double *hiy) {   printf("Enter the number of darts to be thrown in this simulation: ");   scanf("%ld",&N);   double xmax, xmin, ymax, ymin;   GetBorders(&xmin, &xmax, &ymin, &ymax);   double rectArea = (xmax -xmin) * (ymax - ymin);   double estRectArea = 0.0;    double xdart;   double ydart;   int i = 1;   double nhit = 0; //hits can't be anything but integers   //loop goes here:   *lowx=*lowy=0;   *hix=*hiy=0;   while (i <= N) {       i++;       //generate random number between xmin and xmax       xdart = RandNumInRange(xmin,xmax);       if(xdart<*lowx)         *lowx=xdart;       if(xdart>*hix)         *hix=xdart;        //generate random number between ymin and ymax       ydart = RandNumInRange(ymin,ymax);       if(ydart<*lowy)         *lowy=ydart;       if(ydart>*hiy)         *hiy=ydart;       if(DartHits(xdart,ydart)) {         nhit++;       }   }   estRectArea = rectArea * (nhit/ *N);   return estRectArea;      } void analysis(double estRectArea, unsigned long N, double xmin, double xmax, double ymin, double ymax,   double lowx, double lowy, double hix, double hiy, double nhits) {    double percentError = 0.0;   double error = 0;   double actualArea = (ymax-ymin) * (xmax-xmin);   printf("Rectangle has length of %f and a width of %f\n",ymax-ymin,xmax-xmin);   printf("Area of the rectangle is: %f\n",actualArea);   printf("Darts thrown: %ld. Hits: %f, hit percentage: %f%\n\n",N,nhits,((double)nhits/N)*100);   error = abs(actualArea - estRectArea);   printf("Estimated Rectangular Area: %f Error in Area: %f\n",estRectArea,error);   percentError = (error/actualArea) * 100;   printf("Percent error was: %f%\n",percentError);  } /*  What Analysis function should do: 1. Length and width of enclosing rectangle 2. Area of enclosing rectangle 3. Number of darts thrown 4. How many darts hit the shape 5. Percentage of darts that hit the shape 6. Area of the shape computed by out dart throwing 7. Actual area of shape as known from an equation 8. The absolute value difference between these quantities (i.e., the error) */```
• 10-01-2012
Click_here
In ThrowDarts 'N' is a pointer and you are treating it like a normal variable.

For the seg fault - change these 2 things in ThrowDarts():
Code:

```scanf("%ld",&N); //Remove '&' because the value in N is already "the address of" something while (i <= *N)  //Dereference 'N', because 'N' is a pointer```
• 10-01-2012
jsuite
ok fixed those, got this warning:

mcint2.c: In function ‘analysis’:
mcint2.c:111:4: warning: unknown conversion type character 0xa in format [-Wformat]
mcint2.c:117:4: warning: unknown conversion type character 0xa in format [-Wformat]

And when I compile it, I get:

Enter the integer for the seed: 10
Enter the number of darts to be thrown in this simulation: 20

Program stops after this. I think there is a problem with yhi, ylow, xhi, xlow... these are the same as xmax xmin ymin ymax? Except the hi's and lows don't actually have a variable..

Thanks so much for the help.
• 10-01-2012
You should be receiving no warnings - if you are, something probably didn't get changed correctly.

lowy, lowx, hiy and hix are used to record the DART low and high values. xmin, ymin xmax and ymax are the actual BOX borders.

I'm not sure what you mean by "they don't actually have a variable".

I'll be looking at it some more, soon. See what it needs to run.

When is this due, in Pacific Daylight Time?
• 10-01-2012
jsuite
Exactly four hours from now. I think 10pm pacific. I live in U.S. central, its 8:00pm here, and its due at 12pm. And I think it has to do with N being read in as unsigned long int. I've tried fixing it, but I'm so gassed. Went to a tutor today that didn't even know data types. Lol.... But I do know the %ul wasn't working as a data type, but it recognized ul, ull, and i think ld. It's conflicting because we are using a long unsigned int in double estRectArea. Also, when I used a debugger that shows logic errors, it said estRectArea is never used... OR it said estRectArea never used by main()? Can't remember. Sorry I've given sloppy responses, I'm so gassed. Lost alot of sleep working on this past few days (lol). If there's one thing I know for sure, this goes back on the professor. We hadn't even learned about functions asn passing variables in c, but this was assigned. I figured a lot of stuff out on my own and using the book, but why should I pay for a course if the teacher isn't doing anything? I even skipped my classes today to work on this... Not angry, just dissapointed I REALLY thought I would have gotten this done earlier than today.. Oh well, learning experience right? /rant
• 10-01-2012
jsuite
Opps meant it recognised llu and lu. not ul and ull.
• 10-01-2012
I'm tweaking a bunch of stuff up - there were errors ! :(

It's running now, but has some calculations still off. I'll post up the fix, in 40 minutes - 7:00 my time, 9:00 p.m. yours. Maybe rest until then?
• 10-01-2012
jsuite
Thank you so much! Your help is really appreciated, you have no clue. Seriously, not to go over bored, but I'm so humbled you've went out of your way to help someone on a forum.
• 10-01-2012
Unfortunately, the program is still bonkers. Found out the ydart value is out of range (way too low), but have not fixed it.

Anyway:
Code:

``` #include <stdio.h> #include <stdlib.h> #include <math.h> #define PI 3.14159 #define RADIUS 10         double RandNumInRange (double, double); int DartHits(double, double); double ThrowDarts(unsigned long *, double *, double *, double *, double *); void analysis(double,unsigned long,double,double,double,double,double,   double,double,double,unsigned long);         int main (void) {   int seed;   unsigned long N; //number of darts to be thrown   double estRectArea;   double lowx, lowy, hix, hiy;      printf("Enter the integer for the seed: ");   scanf("%d",&seed);   srand(seed);        estRectArea = ThrowDarts(&N,&lowx,&lowy,&hix,&hiy);    printf("\n");   return 0; } void GetBorders(double *xmin, double *xmax, double *ymin, double *ymax) {   double a, b, c, d;       a = 27;   b = 58;   c = 3;   d = 30;       *xmin = a;   *xmax = b;   *ymin = c;   *ymax = d; } double RandNumInRange (double z, double w) { //where w is any max value, and z is any min value   double rn;         rn = ((double)rand()/(double)RAND_MAX)*(w-z);         return rn; }   int DartHits(double x, double y) {   double distance = sqrt(x*x + y*y);       if (distance <= RADIUS) {       return 1;   }   else {       return 0;   } } double ThrowDarts(unsigned long *N,double *lowx,double *lowy,double *hix,double *hiy) {     printf("Enter the number of darts to be thrown in this simulation: ");   scanf("%ul",N);     double xmax, xmin, ymax, ymin;   GetBorders(&xmin, &xmax, &ymin, &ymax);   printf("\nCheck: xmax: %f, xmin: %f, ymax: %f, ymin: %f\n\n",xmax,xmin,ymax,ymin); getchar();   double rectArea = (xmax -xmin) * (ymax - ymin);   double estRectArea = 0.0;    double xdart;   double ydart;   int i = 1;   unsigned long nhit = 0; //hits can't be anything but integers       //loop goes here:   *lowx=*lowy=1000;   *hix=*hiy=0;   //printf("   while (i <= *N) {       //generate random number between xmin and xmax       xdart = RandNumInRange(xmin,xmax);       printf("xdart: %f\n",xdart); getchar();       if(xdart<*lowx)         *lowx=xdart;       if(xdart>*hix)         *hix=xdart;        //generate random number between ymin and ymax       ydart = RandNumInRange(ymin,ymax);       printf("ydart: %f\n",ydart); getchar();       if(ydart<*lowy)         *lowy=ydart;       if(ydart>*hiy)         *hiy=ydart;       if(DartHits(xdart,ydart)) {         nhit++;       }       ++i;   }   printf("lowx: %f, lowy: %f, hix: %f, hiy: %f\n\n",*lowx,*lowy,*hix,*hiy); getchar();   estRectArea = rectArea * (double) nhit/ *N;   analysis(estRectArea, *N,xmin,xmax,ymin,ymax,*lowx,*lowy,*hix,*hiy,nhit);     return estRectArea;  //no reason for this return, imo    } void analysis(double estRectArea, unsigned long N, double xmin,double xmax,double ymin,double ymax,   double lowx,double lowy,double hix, double hiy, unsigned long nhit) {      double percentError = 0.0;   double error = 0.0;   double actualArea = (ymax-ymin) * (xmax-xmin);     printf("Rectange has length of %.2f and a width of %.2f\n\n",ymax-ymin,xmax-xmin);   printf("Area of the rectangle is: %.2f\n\n",actualArea);   printf("Darts thrown: %lu. Hits: %lu, hit percentage: %.2f %%\n\n",N,nhit,(double)nhit/N*100);     error = abs(actualArea - estRectArea);   printf("Estimated Rectangular Area: %.2f Error in Area: %.2f\n\n",estRectArea,error);   percentError = (error/actualArea) * 100;   printf("Percent error was: %.2f %%\n",percentError); }```
I'm going to hunt down that ydart problem, asap. Just found out about it a few minutes ago.

I've got some debug helper print lines of code in there, which stop the program. Just hit enter to go to the next stopping point.

And thanks for bringing such an interesting (if a tad cryptic) problem. Of course, you're welcome.

If I get that ydart problem ID'd, I'll reply.
• 10-01-2012
jsuite
Sweet... Does this possibly have anything to do with it:

* Make start at particular value by adding starting value in
(will change ending value by same amount, so be prepared for that)

Part of the instruction for rand function. ^^

• 10-01-2012
Quote:

Originally Posted by jsuite
Sweet... Does this possibly have anything to do with it:

* Make start at particular value by adding starting value in
(will change ending value by same amount, so be prepared for that)

Part of the instruction for rand function. ^^

Yes, it did. I've fixed that problem, but now hits is not registering correctly. I'll reply in 30 minutes. Wait for that.
Show 80 post(s) from this thread on one page
Page 3 of 5 First 12345 Last