Skip to content

Commit 56793e3

Browse files
authored
Happy Pi Day - calculating Pi
1 parent 51354d1 commit 56793e3

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed

Happy Pi Day.ipynb

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# Happy Pi Day!\n",
8+
"\n",
9+
"### Two Ways to Calculate Pi: \n",
10+
"Real pi = 3.14159265359\n",
11+
"\n",
12+
"### 1. percentage of unit square random points that lie in unit circle\n",
13+
"This method is only as good as our random number generator. And with number of iterations the accuracy improves, up to about 1 million."
14+
]
15+
},
16+
{
17+
"cell_type": "code",
18+
"execution_count": 9,
19+
"metadata": {},
20+
"outputs": [
21+
{
22+
"name": "stdout",
23+
"output_type": "stream",
24+
"text": [
25+
"3.1419916\n"
26+
]
27+
}
28+
],
29+
"source": [
30+
"import random\n",
31+
"in_square = in_circle = pi = 0\n",
32+
"\n",
33+
"for i in range(10000000):\n",
34+
" x = random.random()\n",
35+
" y = random.random()\n",
36+
" dist = (x*x + y*y) ** 0.5\n",
37+
"\n",
38+
" in_square += 1\n",
39+
" if dist <= 1.0:\n",
40+
" in_circle += 1\n",
41+
" \n",
42+
"pi = 4 * in_circle / in_square\n",
43+
"print(pi)"
44+
]
45+
},
46+
{
47+
"cell_type": "markdown",
48+
"metadata": {},
49+
"source": [
50+
"### 2. using series addition\n",
51+
"pi = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 - 4/15 ... \n",
52+
"This method is the more accurate of the two, and is faster. Its accuracy only depends on the size of n."
53+
]
54+
},
55+
{
56+
"cell_type": "code",
57+
"execution_count": 10,
58+
"metadata": {},
59+
"outputs": [
60+
{
61+
"name": "stdout",
62+
"output_type": "stream",
63+
"text": [
64+
"3.1415924535897797\n"
65+
]
66+
}
67+
],
68+
"source": [
69+
"pi = 0.0\n",
70+
"for i in range(1, 10000000, 4):\n",
71+
" pi += 4/i\n",
72+
" pi -= 4/(i+2)\n",
73+
"print(pi)"
74+
]
75+
},
76+
{
77+
"cell_type": "code",
78+
"execution_count": null,
79+
"metadata": {},
80+
"outputs": [],
81+
"source": []
82+
}
83+
],
84+
"metadata": {
85+
"kernelspec": {
86+
"display_name": "Python 3",
87+
"language": "python",
88+
"name": "python3"
89+
},
90+
"language_info": {
91+
"codemirror_mode": {
92+
"name": "ipython",
93+
"version": 3
94+
},
95+
"file_extension": ".py",
96+
"mimetype": "text/x-python",
97+
"name": "python",
98+
"nbconvert_exporter": "python",
99+
"pygments_lexer": "ipython3",
100+
"version": "3.7.0"
101+
}
102+
},
103+
"nbformat": 4,
104+
"nbformat_minor": 2
105+
}

0 commit comments

Comments
 (0)