106 lines
2.2 KiB
Plaintext
106 lines
2.2 KiB
Plaintext
|
|
{
|
||
|
|
"cells": [
|
||
|
|
{
|
||
|
|
"cell_type": "markdown",
|
||
|
|
"metadata": {},
|
||
|
|
"source": [
|
||
|
|
"# Happy Pi Day!\n",
|
||
|
|
"\n",
|
||
|
|
"### Two Ways to Calculate Pi: \n",
|
||
|
|
"Real pi = 3.14159265359\n",
|
||
|
|
"\n",
|
||
|
|
"### 1. percentage of unit square random points that lie in unit circle\n",
|
||
|
|
"This method is only as good as our random number generator. And with number of iterations the accuracy improves, up to about 1 million."
|
||
|
|
]
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"cell_type": "code",
|
||
|
|
"execution_count": 9,
|
||
|
|
"metadata": {},
|
||
|
|
"outputs": [
|
||
|
|
{
|
||
|
|
"name": "stdout",
|
||
|
|
"output_type": "stream",
|
||
|
|
"text": [
|
||
|
|
"3.1419916\n"
|
||
|
|
]
|
||
|
|
}
|
||
|
|
],
|
||
|
|
"source": [
|
||
|
|
"import random\n",
|
||
|
|
"in_square = in_circle = pi = 0\n",
|
||
|
|
"\n",
|
||
|
|
"for i in range(10000000):\n",
|
||
|
|
" x = random.random()\n",
|
||
|
|
" y = random.random()\n",
|
||
|
|
" dist = (x*x + y*y) ** 0.5\n",
|
||
|
|
"\n",
|
||
|
|
" in_square += 1\n",
|
||
|
|
" if dist <= 1.0:\n",
|
||
|
|
" in_circle += 1\n",
|
||
|
|
" \n",
|
||
|
|
"pi = 4 * in_circle / in_square\n",
|
||
|
|
"print(pi)"
|
||
|
|
]
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"cell_type": "markdown",
|
||
|
|
"metadata": {},
|
||
|
|
"source": [
|
||
|
|
"### 2. using series addition\n",
|
||
|
|
"pi = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13 - 4/15 ... \n",
|
||
|
|
"This method is the more accurate of the two, and is faster. Its accuracy only depends on the size of n."
|
||
|
|
]
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"cell_type": "code",
|
||
|
|
"execution_count": 10,
|
||
|
|
"metadata": {},
|
||
|
|
"outputs": [
|
||
|
|
{
|
||
|
|
"name": "stdout",
|
||
|
|
"output_type": "stream",
|
||
|
|
"text": [
|
||
|
|
"3.1415924535897797\n"
|
||
|
|
]
|
||
|
|
}
|
||
|
|
],
|
||
|
|
"source": [
|
||
|
|
"pi = 0.0\n",
|
||
|
|
"for i in range(1, 10000000, 4):\n",
|
||
|
|
" pi += 4/i\n",
|
||
|
|
" pi -= 4/(i+2)\n",
|
||
|
|
"print(pi)"
|
||
|
|
]
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"cell_type": "code",
|
||
|
|
"execution_count": null,
|
||
|
|
"metadata": {},
|
||
|
|
"outputs": [],
|
||
|
|
"source": []
|
||
|
|
}
|
||
|
|
],
|
||
|
|
"metadata": {
|
||
|
|
"kernelspec": {
|
||
|
|
"display_name": "Python 3",
|
||
|
|
"language": "python",
|
||
|
|
"name": "python3"
|
||
|
|
},
|
||
|
|
"language_info": {
|
||
|
|
"codemirror_mode": {
|
||
|
|
"name": "ipython",
|
||
|
|
"version": 3
|
||
|
|
},
|
||
|
|
"file_extension": ".py",
|
||
|
|
"mimetype": "text/x-python",
|
||
|
|
"name": "python",
|
||
|
|
"nbconvert_exporter": "python",
|
||
|
|
"pygments_lexer": "ipython3",
|
||
|
|
"version": "3.7.0"
|
||
|
|
}
|
||
|
|
},
|
||
|
|
"nbformat": 4,
|
||
|
|
"nbformat_minor": 2
|
||
|
|
}
|