Skip to content

Instantly share code, notes, and snippets.

@pon-x
Created November 16, 2020 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pon-x/c750996482a223f85df319c9fd4dc515 to your computer and use it in GitHub Desktop.
Save pon-x/c750996482a223f85df319c9fd4dc515 to your computer and use it in GitHub Desktop.
ルート2のシミュレーション
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## $\\sqrt{2}$をシミュレーション<br>\n",
"<br>\n",
"例えば、長さ4のメジャーから1点を選び、2より大きいか小さいかを考えます。<br>\n",
"ただし、1点を選ぶ条件は0 ~ 2までの小数をランダムに選ぶものとし、それを2乗した値で上記の条件を比較します。<br>\n",
"<br>\n",
"選ばれた値をAとし、もし$A^2$が2以下であれば、選ばれた点は$\\sqrt{2}$以下ということになります。<br>\n",
"<br>\n",
"この選ばれる点が$\\sqrt{2}$以下である確率は、$\\frac{\\sqrt{2}}{2}$となりますから、この結果に2をかければ$\\sqrt{2}$になることが想定されます。"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"%matplotlib inline\n",
"import matplotlib.pyplot as plt\n",
"import random\n",
"import math\n",
"\n",
"\n",
"def prob(num):\n",
" # num個のリストを作る。\n",
" # 要素は0から2までの小数の乱数の2乗が2より小さければTrue、大きければFalseとする。\n",
" point = [random.uniform(0 , 2) ** 2 < 2 for i in range(num)]\n",
"\n",
" # Trueの数を数える\n",
" T = point.count(True)\n",
"\n",
" # 分母の2をとるために、2をかける。\n",
" return T / len(point) * 2"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1.37"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# 試しに、100回試行\n",
"prob(1000)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'10回試行した結果': 1.4,\n",
" '100回試行した結果': 1.38,\n",
" '1000回試行した結果': 1.478,\n",
" '10000回試行した結果': 1.4158,\n",
" '100000回試行した結果': 1.41794}"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# 試行回数を増やして、理論値に近似させる。\n",
"\n",
"sqrt_2 = {}\n",
"\n",
"for i in range(1 ,6):\n",
" x = 10 ** i\n",
" sqrt_2[\"{}回試行した結果\".format(x)] = prob(x)\n",
" \n",
"sqrt_2"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"理論値:1.4142135623730951\n"
]
}
],
"source": [
"print(\"理論値:{}\".format(math.sqrt(2)))"
]
}
],
"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.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment