Hi! Me again ( .)‿( .)
Hopefully it's something more interesting this time.
So I want to write the program that computes a delicious Pie via this "random" number generation.
The math behind this is as follows:
-We have a circle with radius 1.
-That circle is drawn inside a square with sides 2x2.
-Imagine you throw darts at that construction.
-If you throw enough darts [n] at the construction then
[n - total darts thrown]/[in - darts inside the circle] = [4 - area of the square]/[a - area of the circle]
-From that we can calculate our dessert using π=a/r
2
-Since r=1 and area of the square is 4, we can simply find 1 quadrant, it would be easier.
-The formula then is just 4*[a/4]/r
2, i.e. ([in/n]*4)
-[a/4] is [in - darts inside the circle]/[n - total darts thrown]
- We can check if the darts are in the circle using d
2=x
2+y
2, where x and y are randomly generated coordinates of the dart.
The code I created is this:
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 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <Windows.h>
#include <cmath>
#include <stdlib.h>
#include <ctime>
using namespace std;
double Pie ()
{
srand(time(0)); //initiate the seed
int n=0;
cout << "How many darts ye wanna throw? \n";
cin >> n;
int in = 0; //set variable for darts inside the circle
if (n<0) {cout << "FAKer! Ye can't throw negative darts, they won't stick! \n"; return NULL;} //Politely inform the user that they have entered a wrong value.
else
{
for (int i= 0; i<n; i++)
{
double x = rand() / RAND_MAX; //Initiate random variables for coordinates of the dart between 0 and 1
double y = rand() / RAND_MAX;
if (sqrt(x*x + y*y) < 1) in++; // Check if the distance to origin is less than radius and add correct darts to the [in]
}
}
return (in/static_cast<double>(n)*4); //[a/4] is [in/n] so pi=[in/n]*4
}
int main () //Print that crap
{
double t = Pie();
t != 0 ? cout << t : cout << "Error";
Sleep(5000);
return 0;
}
|
However it does not give value close to Pi even if I enter some 5 million or something. It gives a value close to 4 instead. I am struggling with finding a mistake in the code, maybe someone can help?
Please ignore the lousy error catching. I don't know how to do that properly yet and I also deliberately use methods I have just learned so I remember them better.
PS: These forums really need a [list][/list] functionality.