Class Program... (Assignment, C++)

Mac Osxtopus

Registered
YArggh!! stupid thing!

We have to make a program that aproximates pi to...the 100th digit?

I tried using the monte carlo method, but i'm stuck after this, have a look at the code:

#include iostream.h // forum doesn't like alligators, so any blanks
#include math.h // are just made by the forum.
#include stdlib.h

main()
{
double x= rand(); // the x, y co-ordinates of where it is in the square.
double y = rand();
float dist = sqrt(x*x + y*y);// the distance, to calculate the hypotenuse.
long double n; // ...counter or something?
long double N = 100000;
int other=0; // had put it in to try to stop main() from ending.

if(x < 0 || x > 1) { // ... x and y have to be between 1 and 0, including 1 and 0, of course
x = rand();
dist = sqrt(x*x + y*y);
}
if(y > 1 || y < 0 ) {
y = rand();
dist = sqrt(x*x + y*y);
}
if(dist <= 1) {
for(n=0;n<N;n++) {
cout << n << '\n';
}
}
if(50==other) {
return 0;
}

}
 
To approximate pi to the 100th digit using monte carlo would be near impossible for you using this method. Using like 1,000,000,000 darts you are still only likely to be exact to like 6-10 places of pi which is nowhere near 100. You are going to have to go way above INT_MAX to even get close. I suggest you think of all other possibilities first before attempting to use monte carlo if you need to be that exact unless your teacher says that you have to use monte carlo.


As for your monte carlo code I wont post my version as that would be cheating but I will give you some tips.

1. Do you know how to generate random numbers between any two digits a and b? You need to make sure that x and y are inside the box that contains the circle that you are measuring or you have no reliable way of measuring pi.
2. That series of if statements you have at the bottom there is unneccesary if you generate random numbers correctly and then do the correct test, you should only end up using 1 if statement in the simplest version.




I don't know how much experience you have had using monte carlo methods but I really suggest that you do a little reading about it so you can see what your mistakes are as they are pretty severe interms of performance and logic.
 
Back
Top