Every year on March the 14th, for one day the world gets irrationally excited about the famous constant . As is tradition, you try to calculate in unusual ways, demonstrating the constant’s ubiquity as it crops up in the most unexpected circumstances.

lnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
nJ$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$w
`v$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
n$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$z
u$$mnn: Y$$$i .@$$$$$,
$$n )$$$* W$$$$$m
-n[ $$$$. ]$$$$$$
h$$$w $$$$$$Y
[$$$$ X$$$$$$
"$$$$n '$$$$$${
.$$$$$ 8$$$$$$
*$$$$} :$$$$$$+
#$$$$u $$$$$$%
t$$$$$$ ;$$$$$$`
u$$$$$$! $$$$$$W
Y$$$$$$M .$$$$$$,
f$$$$$$$$. Z$$$$$Z nn
`w$$$$$$$$| $$$$$$( v$z
n$$$$$$$$$W $$$$$$$1 'X$8
Y$$$$$$$$$$ *$$$$$$$8nnnn$$$p
$$$$$$$$$@. W$$$$$$$$$$$$$n
_$$$$$$${ x$$$$$$$$$0>
-n{. !|nt_.

A fairly well-known way to approximate pi is to randomly choose points in a square (often thought of as throwing darts at a square piece of cardboard), determine their distance to a circle’s center and do a division, as I did in my Ď€ Generator post.

However, does not only appear in the formula for a circle’s area, , yet also in the formula for a sphere’s volume, , and for all the infinite hyperspheres above dimension three (view this Wikipedia article for more about volumes of higher-dimensional spheres).

In particular, the formula for the hypervolume of a hypersphere in four dimensions is defined as being . Using this formula, my Python script randomly chooses four-dimensional points (each in the interval ), calculates their distance to the point and determines if they are in the hypersphere around that point with radius .

By dividing the number of random points which lie in the hypersphere by the number of iterations used ( in the example below), the script approximates the hypersphere’s hypervolume. By then rearranging the equation with to , the desired constant can be approximated.

```
$ python pi.py
3.14196371717
```

```
# Python 2.7.7 Code
# Jonathan Frech, 13th of March 2017
```

```
# import
import random, math
# number of iterations
n = 10**6
# 4-dimensional, random point
ran = lambda:[random.random() for _ in range(4)]
# test if point is in circle with radius .5 around (.5, .5, .5, .5)
cir = lambda r:math.sqrt(sum(map(lambda x:(x-.5)**2, r))) <= .5
# calculate number of times where point is in circle
i = sum([cir(ran()) for _ in range(n)])
# print pi
print math.sqrt(32.*i/n)
```

### Like this:

Like Loading...