I found this to be very cool. I wrote a paper on AI and the Monte Carlo Method in college so I found it even more interesting. Not a very efficient method of calculating PI but really trivial because of the accuracy of PI as the cycles increase. Did you come up with this on your own? Is this based on the Buffon pin drop method, where he drops a pin of length X on a page of parallel lines? If so bravo I found it really entertaining :)
Also the use of srand and rand (forcing the random number to be less than 1 but greater than zero) is pretty sweet. I wouldn't have thought of that.
Buffon's Needle Experiment:
If we have a uniform grid of parallel lines, unit distance apart and if we drop a needle of length k < 1 on the grid, the probability that the needle falls across a line is 2k/pi. Various people have tried to calculate by throwing needles. The most remarkable result was that of Lazzerini (1901), who made 34080 tosses and got
PI = 355/113 = 3.1415929
on Thurs Feb 15 2001 at 16:40 (EST)
I actually did some testing on this, and it is pretty random, I plugged in a bunch of numbers, and got 3.14... with the cycle 754854. I retested the numbers and I got some results:
$yespi / cycle * 4 = PI
593360 / 754854 * 4 = is 3.14423716374292
593195 / 754854 * 4 = is 3.14336282247958
592995 / 754854 * 4 = is 3.14230301488765
The problem here is not srand. Think of an x,y plane with a 1x1 square with its center located at (0,0). Inside this square is a circle with a radius of 1, also with its center at (0,0)
what is happening in this algorithm is you are coming up with two random numbers but only couting your $yespi if (x^2 + y^2) <=1 . This could be any
coordinate inside the square, therefore all of the points outside the circle but inside the square will not equal pi. But everything inside the circle will. You get a number close to PI
more often than not because the area within the circle is greater than that outside of the circle but within the square. Does this make sense?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] ||