Mathematica, 42 40 39 bytes (or 31/29?)
I've got three solutions all at 42 bytes:
4Count[1~RandomReal~{#,2},p_/;Norm@p<1]/#&
4Tr@Ceiling[1-Norm/@1~RandomReal~{#,2}]/#&
4Tr@Round[1.5-Norm/@1~RandomReal~{#,2}]/#&
They are all unnamed functions that take the number of samples n
andd return a rational approximating π. First they all generate n
points in the unit square in the positive quadrant. Then they determine the number of those samples that lie within the unit circle, and then they divide by the number of samples and multiply by 4
. The only difference is in how they determine the number of sampples inside the unit circle:
- The first one uses
Count
with the condition that Norm[p] < 1
.
- The second one subtracts the norm of each point from
1
and then rounds up. This turns numbers inside the unit circle to 1
and those outside to 0
. Afterwards I just sum them all up with Tr
.
- The third one does essentially the same, but subtracts the from
1.5
, so I can use Round
instead of Ceiling
.
Aaaaaand while writing this up, it occurred to me that there is indeed a shorter solution, if I just subtract from 2
and then use Floor
:
4Tr@Floor[2-Norm/@1~RandomReal~{#,2}]/#&
or saving another byte by using the Unicode flooring or ceiling operators:
4Tr@⌊2-Norm/@1~RandomReal~{#,2}⌋/#&
4Tr@⌈1-Norm/@1~RandomReal~{#,2}⌉/#&
Note that the three rounding-based solutions can also be written with Mean
instead of Tr
and without the /#
, again for the same bytes.
If other Monte Carlo based approaches are fine (specifically, the one Peter has chosen), I can do 31 bytes by estimating the integral of √(1-x2)
or 29 using the integral of 1/(1+x2)
, this time given as a floating point number:
4Mean@Sqrt[1-1~RandomReal~#^2]&
Mean[4/(1+1~RandomReal~#^2)]&
((0..4e9).map{rand**2+rand**2<1}.to_s.sub(/./,"$1.")
\$\endgroup\$map
give you an array oftrue
andfalse
? \$\endgroup\$.filter{...}.size
should work, though. \$\endgroup\$