I’ve already made an article on the 2D version of this problem, if you want to check it out before this one, you can visit https://www.mattiagiuri.com/2020/04/21/a-very-notorious-problem/.
Now, the 3D version says: if you have 3 reals x, y, z chosen randomly between 0 and 1, what’s the probability that
It’s important to notice that any point in space with coordinates (x, y, z) lies within a cube with side length equal to 1 and with a vertex on the origin.
Furthermore, any point satisfying the target condition, lies within the octave of sphere with center on the origin and radius equal to 1.
Hence the probability is the ratio of the volume of the octave of sphere and the volume of the cube, or
Python Implementation Of A Pi Approximation
import random
precision = 10000000
count = 0
for i in range(precision):
if pow(random.uniform(0, 1), 2) + pow(random.uniform(0, 1), 2) + pow(random.uniform(0, 1), 2) <= 1:
count = count + 1
print(6 * float(count)/precision)
This code is pretty straightforward, we’re just counting on average how many times the point lies in the octave of sphere and printing the result multiplied by six to get pi.
The output is:
3.1416582