### Buffon Needle Experiment I'm doing a text book problem where we simulate PI using the "Buffon Needle Experiment" and I can't figure out what i am doing wrong.
The problem says you need to generate two random numbers:
-one to describe the starting position of the needle.
-one to describe the angle of the needle with the x-axis.
Then it says to generate the lower point of the needle; ylow, to be any random number between 0 and 2.
The angle between the needle and the x-axis can be any value between 0 to 18- degrees (PI radians).
The upper end of the needle is: yhigh = ylow + sin angle.

They then want to run a look 10,000 times and giving a hot if yhigh is at least 2. After 10,000 tries print cout tries / angle.

When i do this i get an inf error and i believe it has something to do with the angle being randomly generated to zero and possibly a diving by zero error at the end of the program. My code is as follows:
 ``123456789101112131415161718192021222324252627282930`` ``````#include #include #include #include using namespace std; int main() { double start = 0; double angle = 0; double ylow = 0; double yhigh = 0; double hits = 0; double tries = 0; srand(time(0)); const double PI = 3.141592653589793238; for (int i = 0; i < 10000; i++) { ylow = rand() % 2; angle = rand() % 180; yhigh = ylow + sin(angle); tries++; if (yhigh >= 2) { hits++; } } cout << tries / hits; return 0; }`````` Do you know what a debugger is?
Now is the time to find out what debugging options are available on your system. If you're using visual studio, it's all point and click.

> and possibly a diving by zero error at the end of the program.
You don't need to guess, you can find this out for yourself.

Your first skill to master being setting breakpoints and printing variables. You can learn a lot from your program simply by stopping and having a look to see if what the machine has done matches your expectation.
 ``12345678910111213`` ``````\$ gdb -q ./a.out Reading symbols from ./a.out...done. (gdb) b 28 Breakpoint 1 at 0x4009b3: file baz.cpp, line 28. (gdb) run Starting program: ./a.out Breakpoint 1, main () at baz.cpp:28 28 cout << tries / hits; (gdb) p tries \$1 = 10000 (gdb) p hits \$2 = 0``````

So yes, you have zero hits.

> yhigh = ylow + sin(angle);
First of all, sin() takes radians as the parameter, not degrees. So half your sin() results will be negative to begin with.

Second, given that ylow is either 0 or 1, there is only one specific value (PI/2) where sin() would return anything close to being actually 1 in order for your >= 2 test to succeed.