Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in / Register
Toggle navigation
N
numer-60-2
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Littichai Buddaken
numer-60-2
Commits
f7f9d76a
Commit
f7f9d76a
authored
Apr 19, 2018
by
Littichai Buddaken
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
add week12(edited)&week13
parent
a67cb5bd
Hide whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
1417 additions
and
0 deletions
+1417
-0
Numerical Integration-checkpoint.ipynb
....ipynb_checkpoints/Numerical Integration-checkpoint.ipynb
+405
-0
Numerical Integration.ipynb
week12/Numerical Integration.ipynb
+500
-0
Initial-Value-checkpoint.ipynb
week13/.ipynb_checkpoints/Initial-Value-checkpoint.ipynb
+256
-0
Initial-Value.ipynb
week13/Initial-Value.ipynb
+256
-0
No files found.
week12/.ipynb_checkpoints/Numerical Integration-checkpoint.ipynb
0 → 100644
View file @
f7f9d76a
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"# Numerical Integration\n",
"\n",
"> คำนวณค่า $\\int_{a}^{b}f(x)dx$ เมื่อกำหนดฟังก์ชัน $f(x)$ มาให้\n",
"\n",
"คำนวณหาพื้นที่ใต้กราฟ $f(x)$ จากในช่วง $x \\in [a,b]$ โดยปกติแล้วจะใช้วิธีประมาณค่าโดยการแบ่งพื้นที่ออกเป็นช่วงๆ แต่ละช่วงจะเป็นสี่เหลี่ยมแล้วรวมพื้นที่สี่เหลี่ยมเหล่านั้นมาประมาณค่าพื้นที่ใต้กราฟหรือค่า $\\int_{a}^{b}f(x)dx$ นั่นเอง\n",
"\n",
"1. แบ่งเป็นสี่เหลี่ยมที่มีความกว้างเท่ากัน: Newton-Cotes\n",
"\n",
" 1.1. Trapezoidal rule\n",
" \n",
" 1.2. Simpson's rule\n",
" \n",
"2. แบ่งตามความเหมาะสม: Gaussian\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Newton-Cotes\n",
"$$\n",
"I = \\sum_{i=0}^{n}A_if(x_i)\n",
"$$\n",
"where\n",
"$$\n",
"Ai = \\int_{a}^{b}l_i(x)dx, i=0,1,2,...,n \\\\\n",
"x_i \\in [a,b]\n",
"$$\n",
"\n",
"### Trapezoidal rule\n",
"$$\n",
"I_i = [f(x_i) + f(x_{i+1})]\\frac{h}{2} \\\\\n",
"\\int_{a}^{b}f(x)dx \\approx I = \\sum_{i=0}^{n-1}I_i = [f(x_0) + 2f(x_1) + 2f(x_2) + ... + 2f(x_{n-1})+f(x_n)]\\frac{h}{2}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example\n",
"1. จงเขียนโปรแกรมเพื่อหา $\\int_{0}^{3}f(x)dx$ ด้วยวิธี trapezoidal rule โดยกำหนดให้ $f(x) = 3x^2 + 9x + 2$ โดยใช้ $n=4$\n",
"\n",
"```python\n",
"def f(x): return 3*x**2 + 9*x + 2\n",
"def trapezoid(f, a, b):\n",
" pass\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"74.34375"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def f(x): return 3*x**2 + 9*x + 2\n",
"def trapezoid(f, a, b):\n",
" n = 4\n",
" h = (b-a)/n\n",
" #sumI = 0.0\n",
" #for i in [0,1,2,3]:\n",
" # sumI += (1/2)*h*(f(a+i*h) + f(a+(i+1)*h))\n",
" return sum([ (1/2)*h*(f(a+i*h)+f(a+(i+1)*h)) for i in range(4) ]) \n",
"\n",
"trapezoid(f, 0, 3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Simpson's rule\n",
"* Simpson's 1/3 rule (First Simpson's Rule)\n",
"ประมาณค่าพื้นที่ใต้กราฟในแต่ละช่วงด้วย Larange Parabolic Interpolation โดยแต่ละช่วงจะเพิ่มจุดกึ่งกลางเข้าไป\n",
"\n",
"> จาก Larange Interpolation\n",
"> $$\n",
" P_n(x) = \\sum_{i=0}^{n}{y_i l_i (x)} \\\\\n",
" l_i(x) = \\frac{x-x_0}{x_i-x_0}\\cdot\\frac{x-x_1}{x_i-x_1}\\cdots\\frac{x-x_{i-1}}{x_i-x_{i-1}}\\cdot\\frac{x-x_{i+1}} {x_i-x_{i+1}}\\cdots\\frac{x-x_n}{x_i-x_n} \n",
"$$\n",
"\n",
"ถ้าใช้ Larange Interpolation จาก $[a,b]$ จะได้\n",
"$ x_0 = a, x_1 = \\frac{a+b}{2}, x_2 = b $\n",
"เมื่อทำการแทนสมการแล้วลดรูปจะได้\n",
"$$\n",
"l_0(x) = \\frac{(x-x_1)(x-x_2)}{(x_0-x_1)(x_0-x_2)} \\\\\n",
"l_1(x) = \\frac{(x-x_0)(x-x_2)}{(x_1-x_0)(x_1-x_2)} \\\\\n",
"l_2(x) = \\frac{(x-x_0)(x-x_1)}{(x_2-x_0)(x_2-x_1)} \n",
"$$\n",
"พื้นที่ใต้กราฟในแต่ละช่วงคือ\n",
"$$\n",
"A_i = \\int_{a}^{b}l_i(x) = \\int_{-h}^{h}l_i(z)dz\n",
"$$\n",
"เมื่อกำหนดให้ $z_0 = -h, z_1 = 0, z_2 = h$ จะได้\n",
"$$\n",
"$$\n",
"นั่นคือ\n",
"$$\n",
"A_0 = \\int_{-h}^{h}\\frac{(z-0)(z-h)}{(-h)(-2h)}dz = \\frac{1}{2h^2}\\int_{-h}^{h}(z^2-hz)dz = \\frac{h}{3} \\\\\n",
"A_1 = \\frac{4h}{3} \\\\\n",
"A_2 = \\frac{h}{3} \n",
"$$\n",
"> คะแนนพิเศษ derive $A_1, A_2$\n",
"\n",
"$$\n",
"I = \\sum_{i=0}^{2}A_if(x_i) = [f(a) + 4f(\\frac{a+b}{2}) + f(b)]\\frac{h}{3}\n",
"$$\n",
"ดังนั้น first Simpson's rule สำหรับ $n$ ช่วงจึงเขียนได้เป็น\n",
"$$\n",
"I_i = [f(x_i) + 4f(\\frac{x_i+x_{i+1}}{2}) + f(x_{i+1})]\\frac{h}{3} \\\\\n",
"\\int_{a}^{b}f(x)dx \\approx I = [f(x_0) + 4f(x_1) + 2f(x_2) + 4f(x_3) + ... + 2f(x_{n-2}) + 4f(x_{n-1})+f(x_n)]\\frac{h}{3}\n",
"$$\n",
"\n",
"เงื่อนไขของการใช้สมการข้างต้นคือ $n$ ต้องเป็นเลขคู่ ถ้าเป็นเลขคี่แนะนำให้ Simpson's 3/8 rule [Second Simpson's Rule] กับ $x_0, x_1, x_2, x_3$ หรือ $x_{n-3},x_{n-2},x_{n-1},x_n$ ตามสมการต่อไปนี้\n",
"$$\n",
"I = [f(x_0) + 3f(x_1) + 3f(x_2) + f(x_3)]\\frac{3h}{8}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"n,a,b = 4,0,3 \\\\\n",
"h = \\frac{b-a}{n} \\\\\n",
"x_i = x_0 + ih \\\\\n",
"\\int_{a}^{b}f(x)dx = [f(x_0) + 4f(x_1) + 2f(x_2) + 4f(x_3)+f(x_4)]\\frac{h}{3}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example\n",
"1. จงเขียนโปรแกรมเพื่อหา $\\int_{0}^{3}f(x)dx$ ด้วยวิธี Simpson's rule โดยกำหนดให้ $f(x) = 3x^2 + 9x + 2$ และ $n=4$\n",
"\n",
"ตอบ:\n",
"\n",
"```python\n",
"def f(x): return 3*x**2 + 9*x + 2\n",
"def simpson(f, a, b):\n",
" a,b = 0,3\n",
" n = 4\n",
" x0 = a\n",
" h = (b-a)/n\n",
" return (f(x0+0*h) + 4*f(x0+1*h) + 2*f(x0+2*h) + 4*f(x0+3*h) + f(x0+4*h))*h/3\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"73.5"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def f(x): return 3*x**2 + 9*x + 2\n",
"def simpson(f, a, b):\n",
" n = 4\n",
" x0 = a\n",
" h = (b-a)/n\n",
" return (f(x0+0*h) + 4*f(x0+1*h) + 2*f(x0+2*h) + 4*f(x0+3*h) + f(x0+4*h))*h/3\n",
"simpson(f, 0, 3)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def simpson(f, a, b, n):\n",
" h = (b-a)/n\n",
" x0 = a # x_i = x_0 + i*h\n",
" #f(x0) + 4*f(x1) + 2*f(x2) + .... + 4*f(x_n-1) + f(x_n)\n",
" s = f(x0)\n",
" \n",
" # odd - x1, x3, x5, ... \n",
" #s += 4*f(x1) + 4*f(x3) + 4*f(x5) + ...\n",
" for i in range(1,n,2):\n",
" s += 4*f(x0+i*h)\n",
" \n",
" # even - x2, x4, x6, ...\n",
" #s += 2*f(x2) + 2*f(x4) + 2*f(x6) + ...\n",
" for i in range(2,n-1,2):\n",
" s += 2*f(x0+i*h)\n",
" \n",
" s += f(x0+n*h)\n",
" return s*h/3"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(4, 0.6321341753205324),\n",
" (6, 0.6321232596014171),\n",
" (8, 0.6321214146047422),\n",
" (10, 0.6321209095890152),\n",
" (12, 0.6321207280453661),\n",
" (14, 0.6321206501876014),\n",
" (16, 0.6321206123891728),\n",
" (18, 0.6321205922694484),\n",
" (20, 0.6321205807706575)]"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from math import e\n",
"def f(x): return e**(-x)\n",
"a,b = 0,1\n",
"simpson(f, a, b, 4)\n",
"[ (n,simpson(f,a,b,n)) for n in range(4, 22, 2) ]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercise\n",
"\n",
"1. จงเขียนฟังก์ชัน `def simpson(f, a, b, n)` เพื่อคำนวณหาพื้นที่ใต้กราฟของฟังก์ชัน $f$ จากค่า $x=a$ ถึง $x=b$ โดยแบ่งเป็น $n$ ช่วง ดัวยวิธี Simpson's rule\n",
"\n",
"2. จงเขียนฟังก์ชัน `def trapezoid(f, a, b, n)` เพื่อคำนวณหาพื้นที่ใต้กราฟของฟังก์ชัน $f$ จากค่า $x=a$ ถึง $x=b$ โดยแบ่งเป็น $n$ ช่วง ด้วยวิธี trapezoidal rule\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import sympy\n",
"sympy.init_printing()"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def f(x): return 3*x**2 + 9*x + 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(2, 56)"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"f(0), f(3)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from math import e\n",
"z = e**-x"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAALYAAAARBAMAAACCx0thAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAIpm7MhCriUTv3c12\nVGZoascqAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADGUlEQVQ4EbWUz2scZRjHP5Pdmc3uZuMa8KCC\nrlETQaSVGA+ehoIeRMicKm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845905^{- x}$$"
],
"text/plain": [
" -x\n",
"2.71828182845905 "
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"z"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAPAAAAARBAMAAAARYzyGAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEM3dMlTvq5l2Zoki\nu0Rn3bgMAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADUElEQVRIDcWVS0wTURSG/yktQ9spNLpA4qIl\nMTFoDES3Kk1ciHHRrsToAl9xYVDqE2iMVKKBBMNjJQQTutIgCxs1ASHGURNC3Ahx4UaSRpcueAho\nQBjPOXc6Q4C1nMXMud898//3zJ3eAtsQwd4Tt7bBFujRo0c3GWsdQzEHGu3TMjjWNDaWFar1jeSg\ncFl/p13oQsmI1gAV4ZoEdo3dBUTS0+N9aJcj5snkU7r7zsvAk9AOO7QUwTUevLAsKykVRcBtKJyG\nngBOhQEXSkYPHAEarBVoVzBuQiQLLSsL3zTFFFBiUo0dpW1zkj0FXuYZrgOXefAI0CEVZ4APCvsy\nMKJaUwsZu1AywH8V2N9sQj8HPQ2R9Aw/cWQRR8wd+JXxV6COtFRcBFpilGaB1yRHFW+BnRAcnIRW\nBQxQsQslAz4dAJL0XEkUwVmIpK4U+WrMvmLFfNjGv4GZRJ5VhpUxUNytjGemMArBxavhYEYZu1Ay\nWqhtHJmEfwEiuc5Ya/7ZH85bKFn6EP6QMZk4Ua1KQgR4abo1lOE5wi3Lo5Rwxy5UWcAk49TgAxRS\nx2tKUn/eG+MHN4fq2FgB4ll3tpjGHOwhFe/meSWMg1Y5ZWwMF0pWBjKewuccvWfPspIMhQ35Tql6\nQ9jG1LEYa2q6ICl3bZZuXOG7V32NUsa1P5ZyytiFKsuyMRCqQgXOLhp5yS8MndhxiGPPplcdiUpJ\nuyr084iNn8G/RD0SDiQxQL9A7tiFkvliyrjoLwJ9Jxec3esyldiGq+qYv4S6BE2pVv1pVVUwSXeu\nqKcXkgDjQhPeRWXsQsl2g4x13l56SJ9TkjdoQ3I03hy28TQdF9SEHadhmJxGknShCn7legaMI0RS\nYuzC9zJd29i41EzfVREtFJ4kRPIC0OXq0oQTtjH92lsd5k3Db/IonqaL3XHI9DIuNIFvTsc2pI5D\nxHGVT7OCaKAecZMPkFakgYM0sUWwLG1sQUK75Mx+HBu5yRB1aWJc8T2MQQguLkegWxm7UDIqXYVB\nJ5bpL9f20QJYcgK0iq2i6M58ijdWe/M45sxXWtYv2e3xBJ3IXOFtoj8JwTje0Qm0NezNrIMyTUeZ\nlcLE8H1gpD1HZwNLGh1NW79px+w/Jf8Ai2Q6WOYdK4QAAAAASUVORK5CYII=\n",
"text/latex": [
"$$- 1.0 \\cdot 2.71828182845905^{- x}$$"
],
"text/plain": [
" -x\n",
"-1.0⋅2.71828182845905 "
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sympy.diff(z)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"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.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
week12/Numerical Integration.ipynb
0 → 100644
View file @
f7f9d76a
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"# Numerical Integration\n",
"\n",
"> คำนวณค่า $\\int_{a}^{b}f(x)dx$ เมื่อกำหนดฟังก์ชัน $f(x)$ มาให้\n",
"\n",
"คำนวณหาพื้นที่ใต้กราฟ $f(x)$ จากในช่วง $x \\in [a,b]$ โดยปกติแล้วจะใช้วิธีประมาณค่าโดยการแบ่งพื้นที่ออกเป็นช่วงๆ แต่ละช่วงจะเป็นสี่เหลี่ยมแล้วรวมพื้นที่สี่เหลี่ยมเหล่านั้นมาประมาณค่าพื้นที่ใต้กราฟหรือค่า $\\int_{a}^{b}f(x)dx$ นั่นเอง\n",
"\n",
"1. แบ่งเป็นสี่เหลี่ยมที่มีความกว้างเท่ากัน: Newton-Cotes\n",
"\n",
" 1.1. Trapezoidal rule\n",
" \n",
" 1.2. Simpson's rule\n",
" \n",
"2. แบ่งตามความเหมาะสม: Gaussian\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Newton-Cotes\n",
"$$\n",
"I = \\sum_{i=0}^{n}A_if(x_i)\n",
"$$\n",
"where\n",
"$$\n",
"Ai = \\int_{a}^{b}l_i(x)dx, i=0,1,2,...,n \\\\\n",
"x_i \\in [a,b]\n",
"$$\n",
"\n",
"### Trapezoidal rule\n",
"$$\n",
"I_i = [f(x_i) + f(x_{i+1})]\\frac{h}{2} \\\\\n",
"\\int_{a}^{b}f(x)dx \\approx I = \\sum_{i=0}^{n-1}I_i = [f(x_0) + 2f(x_1) + 2f(x_2) + ... + 2f(x_{n-1})+f(x_n)]\\frac{h}{2}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example\n",
"1. จงเขียนโปรแกรมเพื่อหา $\\int_{0}^{3}f(x)dx$ ด้วยวิธี trapezoidal rule โดยกำหนดให้ $f(x) = 3x^2 + 9x + 2$ โดยใช้ $n=4$\n",
"\n",
"```python\n",
"def f(x): return 3*x**2 + 9*x + 2\n",
"def trapezoid(f, a, b):\n",
" pass\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"# โจทย์ f(x)= e^x*sin(X) ,n = 10\n",
"def f(x) :\n",
" from math import e ,sin\n",
" return e**x*sin(x)\n",
"#n คือ จำนวนการแบ่งช่วง\n",
"#h คือ ค่าของช่วงที่แบ่ง from (b-a)/n\n",
"def area1(f,a,h,n):#Findin' area from f , a , h , n \n",
" return sum([(1/2)*h*(f(a+i*h)+f(a+(i+1)*h)) for i in range(n)])\n",
"def area2(f,a,b,n):#Findin' area from f , a , b , n without h\n",
" return sum([(1/2)*((b-a)/n)*(f(a+i*((b-a)/n))+f(a+(i+1)*((b-a)/n))) for i in range(n)])\n",
"area1(f,0.1,0.05,10),area2(f,0.1,0.6,10)\n",
"#Chernaling are you kiddin' me\n",
"#Loadto be the s'one\n"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.2574269780305713 0.2574269780305713\n"
]
}
],
"source": [
"import sympy\n",
"sympy.init_printing()\n",
"a, b =0.1,0.6\n",
"n, h =10,(b-a)/10\n",
"def y(x):return 3*x**2+9*x+2\n",
"print(area1(f,a,h,n),area2(f,a,b,n))"
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAmQAAAAVCAYAAADo8PLxAAAABHNCSVQICAgIfAhkiAAACv1JREFU\neJztnX2QVlUdxz8ICGS2FL2QSa3hG4yNaIlRps9m4WBa9jLmH02uZkWk5RDaQGNub0SWhlkN2FRE\nZTkDg4wjIYiKLoZByWQIWcCDBquJDC8VoUvbH99z57nP3Xvvc+65d5f77J7PzM599rzd83vuOd/n\nnt85517weDwej8fj8Xg8Hk+/8Qvgn8BxOct5O9ADXJO7Rh6Px1MsrUifFhVYZtNp58eAO4BHgQPm\npL9yLOs7wBrgWeAQsBd4ArgZGJOQp2rOGff3XEKeIcCngceBfwH/BjYC04FjYtIXYeMnQvVKuygn\nAj8DdgOHkX3zgVcnpC+jLWNM+DLg7+ha7gc6gU8l1MslT1bbIXt7calXmTgH+B8wMybOpS0sA7qA\nVxZYx6xk7SNJVMmuHX3NYNBTyG+n11Ovp1FaKfaG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R1j5SpbfeuGqHDe2429jB\nwNdTVzuTyvB6OrD11FbzWinOQ1ZG7fR4PE3ObCQQZxVU3nWmvPMKKs/j8XjKiNdOj8dTKCORV+De\nAsoahTx9Sxol9Hg8nianX7RzoL+nzePx1OhGz50agRbRxj3t2pZT0FTGLeR/1pfH4/GUGa+dHo/H\n4/F4PB6Px+PxeDweT5/zf8ACgG8g7vYxAAAAAElFTkSuQmCC\n",
"text/latex": [
"$$- 1.35914091422952 \\cos{\\left (1 \\right )} + 0.5 + 1.35914091422952 \\sin{\\left (1 \\right )}$$"
],
"text/plain": [
"-1.35914091422952⋅cos(1) + 0.5 + 1.35914091422952⋅sin(1)"
]
},
"execution_count": 95,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x,y= sympy.Symbol('x'),sympy.Symbol('y')\n",
"y = 3*x**2+9*x+2\n",
"sympy.integrate(y,(x,0.1,0.6))"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2.79390625"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def f(x): return 3*x**2 + 9*x + 2\n",
"def trapezoid(f, a, b):\n",
" n = 4\n",
" h = (b-a)/n\n",
" #sumI = 0.0\n",
" #for i in [0,1,2,3]:\n",
" # sumI += (1/2)*h*(f(a+i*h) + f(a+(i+1)*h))\n",
" return sum([ (1/2)*h*(f(a+i*h)+f(a+(i+1)*h)) for i in range(4) ]) \n",
"\n",
"trapezoid(f, 0, 3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Simpson's rule\n",
"* Simpson's 1/3 rule (First Simpson's Rule)\n",
"ประมาณค่าพื้นที่ใต้กราฟในแต่ละช่วงด้วย Larange Parabolic Interpolation โดยแต่ละช่วงจะเพิ่มจุดกึ่งกลางเข้าไป\n",
"\n",
"> จาก Larange Interpolation\n",
"> $$\n",
" P_n(x) = \\sum_{i=0}^{n}{y_i l_i (x)} \\\\\n",
" l_i(x) = \\frac{x-x_0}{x_i-x_0}\\cdot\\frac{x-x_1}{x_i-x_1}\\cdots\\frac{x-x_{i-1}}{x_i-x_{i-1}}\\cdot\\frac{x-x_{i+1}} {x_i-x_{i+1}}\\cdots\\frac{x-x_n}{x_i-x_n} \n",
"$$\n",
"\n",
"ถ้าใช้ Larange Interpolation จาก $[a,b]$ จะได้\n",
"$ x_0 = a, x_1 = \\frac{a+b}{2}, x_2 = b $\n",
"เมื่อทำการแทนสมการแล้วลดรูปจะได้\n",
"$$\n",
"l_0(x) = \\frac{(x-x_1)(x-x_2)}{(x_0-x_1)(x_0-x_2)} \\\\\n",
"l_1(x) = \\frac{(x-x_0)(x-x_2)}{(x_1-x_0)(x_1-x_2)} \\\\\n",
"l_2(x) = \\frac{(x-x_0)(x-x_1)}{(x_2-x_0)(x_2-x_1)} \n",
"$$\n",
"พื้นที่ใต้กราฟในแต่ละช่วงคือ\n",
"$$\n",
"A_i = \\int_{a}^{b}l_i(x) = \\int_{-h}^{h}l_i(z)dz\n",
"$$\n",
"เมื่อกำหนดให้ $z_0 = -h, z_1 = 0, z_2 = h$ จะได้\n",
"$$\n",
"$$\n",
"นั่นคือ\n",
"$$\n",
"A_0 = \\int_{-h}^{h}\\frac{(z-0)(z-h)}{(-h)(-2h)}dz = \\frac{1}{2h^2}\\int_{-h}^{h}(z^2-hz)dz = \\frac{h}{3} \\\\\n",
"A_1 = \\frac{4h}{3} \\\\\n",
"A_2 = \\frac{h}{3} \n",
"$$\n",
"> คะแนนพิเศษ derive $A_1, A_2$\n",
"\n",
"$$\n",
"I = \\sum_{i=0}^{2}A_if(x_i) = [f(a) + 4f(\\frac{a+b}{2}) + f(b)]\\frac{h}{3}\n",
"$$\n",
"ดังนั้น first Simpson's rule สำหรับ $n$ ช่วงจึงเขียนได้เป็น\n",
"$$\n",
"I_i = [f(x_i) + 4f(\\frac{x_i+x_{i+1}}{2}) + f(x_{i+1})]\\frac{h}{3} \\\\\n",
"\\int_{a}^{b}f(x)dx \\approx I = [f(x_0) + 4f(x_1) + 2f(x_2) + 4f(x_3) + ... + 2f(x_{n-2}) + 4f(x_{n-1})+f(x_n)]\\frac{h}{3}\n",
"$$\n",
"\n",
"เงื่อนไขของการใช้สมการข้างต้นคือ $n$ ต้องเป็นเลขคู่ ถ้าเป็นเลขคี่แนะนำให้ Simpson's 3/8 rule [Second Simpson's Rule] กับ $x_0, x_1, x_2, x_3$ หรือ $x_{n-3},x_{n-2},x_{n-1},x_n$ ตามสมการต่อไปนี้\n",
"$$\n",
"I = [f(x_0) + 3f(x_1) + 3f(x_2) + f(x_3)]\\frac{3h}{8}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"n,a,b = 4,0,3 \\\\\n",
"h = \\frac{b-a}{n} \\\\\n",
"x_i = x_0 + ih \\\\\n",
"\\int_{a}^{b}f(x)dx = [f(x_0) + 4f(x_1) + 2f(x_2) + 4f(x_3)+f(x_4)]\\frac{h}{3}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example\n",
"1. จงเขียนโปรแกรมเพื่อหา $\\int_{0}^{3}f(x)dx$ ด้วยวิธี Simpson's rule โดยกำหนดให้ $f(x) = 3x^2 + 9x + 2$ และ $n=4$\n",
"\n",
"ตอบ:\n",
"\n",
"```python\n",
"def f(x): return 3*x**2 + 9*x + 2\n",
"def simpson(f, a, b):\n",
" a,b = 0,3\n",
" n = 4\n",
" x0 = a\n",
" h = (b-a)/n\n",
" return (f(x0+0*h) + 4*f(x0+1*h) + 2*f(x0+2*h) + 4*f(x0+3*h) + f(x0+4*h))*h/3\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"73.5"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def f(x): return 3*x**2 + 9*x + 2\n",
"def simpson(f, a, b):\n",
" n = 4\n",
" x0 = a\n",
" h = (b-a)/n\n",
" return (f(x0+0*h) + 4*f(x0+1*h) + 2*f(x0+2*h) + 4*f(x0+3*h) + f(x0+4*h))*h/3\n",
"simpson(f, 0, 3)"
]
},
{
"cell_type": "code",
"execution_count": 97,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def simpson(f, a, b, n):\n",
" h = (b-a)/n\n",
" x0 = a # x_i = x_0 + i*h\n",
" #f(x0) + 4*f(x1) + 2*f(x2) + .... + 4*f(x_n-1) + f(x_n)\n",
" s = f(x0)\n",
" \n",
" # odd - x1, x3, x5, ... \n",
" #s += 4*f(x1) + 4*f(x3) + 4*f(x5) + ...\n",
" for i in range(1,n,2):\n",
" s += 4*f(x0+i*h)\n",
" \n",
" # even - x2, x4, x6, ...\n",
" #s += 2*f(x2) + 2*f(x4) + 2*f(x6) + ...\n",
" for i in range(2,n-1,2):\n",
" s += 2*f(x0+i*h)\n",
" \n",
" s += f(x0+n*h)\n",
" return s*h/3"
]
},
{
"cell_type": "code",
"execution_count": 105,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 4 1.3616491974399736e-05 0.003288870199135485\n",
" 6 2.7007728591321722e-06 0.001462565055180165\n",
" 8 8.557761842498124e-07 0.0008228593819220587\n",
" 10 3.5076045723503313e-07 0.0005266793587330731\n",
" 12 1.6921680812131967e-07 0.0003657681764012155\n",
" 14 9.135904344148571e-08 0.0002687358901396486\n",
" 16 5.356061483219321e-08 0.00020575501594155554\n",
" 18 3.3440890390146194e-08 0.00016257408557796005\n",
" 20 2.1942099470706466e-08 0.0001316862962578158\n"
]
}
],
"source": [
"from math import e\n",
"from sympy import *\n",
"def f(x): return e**(-x)\n",
"a,b = 0,1\n",
"r = 0.632120558828558\n",
"simpson(f, a, b, 4)\n",
"for v in [ (n,simpson(f,a,b,n),area2(f,a,b,n)) for n in range(4, 22, 2) ] :\n",
" print('{:5} {:20} {:20}'.format(v[0],abs(v[1]-r),abs(r-v[2])))"
]
},
{
"cell_type": "code",
"execution_count": 96,
"metadata":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ec3u8Wy69bxIqhDrmcdco0y/GzWHqVvP8MM8wwwwwzzDDDDP9f+B/5DlG+xc4w\nEgAAAABJRU5ErkJggg==\n",
"text/latex": [
"$$0.632120558828558$$"
],
"text/plain": [
"0.632120558828558"
]
},
"execution_count": 96,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from sympy import *\n",
"f = e**(-x)\n",
"integrate(f,(x,0,1))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exercise\n",
"\n",
"1. จงเขียนฟังก์ชัน `def simpson(f, a, b, n)` เพื่อคำนวณหาพื้นที่ใต้กราฟของฟังก์ชัน $f$ จากค่า $x=a$ ถึง $x=b$ โดยแบ่งเป็น $n$ ช่วง ดัวยวิธี Simpson's rule\n",
"\n",
"2. จงเขียนฟังก์ชัน `def trapezoid(f, a, b, n)` เพื่อคำนวณหาพื้นที่ใต้กราฟของฟังก์ชัน $f$ จากค่า $x=a$ ถึง $x=b$ โดยแบ่งเป็น $n$ ช่วง ด้วยวิธี trapezoidal rule\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import sympy\n",
"sympy.init_printing()"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def f(x): return 3*x**2 + 9*x + 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(2, 56)"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"f(0), f(3)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from math import e\n",
"z = e**-x"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAALYAAAARBAMAAACCx0thAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAA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baJ5LZN1k6AmMN8kz/Qp9cJ3GGNUCw/Eapr+hftUbu3p/I7szJNv6F9V1u+lw2OT+ldNnD7b96J5\nbVqNms4ztngvFMblCV/7OiaYbCQD5D1N/wX8wRK5TpgTOQAAAABJRU5ErkJggg==\n",
"text/latex": [
"$$2.71828182845905^{- x}$$"
],
"text/plain": [
" -x\n",
"2.71828182845905 "
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"z"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAPAAAAARBAMAAAARYzyGAAAAMFBMVEX///8AAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAv3aB7AAAAD3RSTlMAEM3dMlTvq5l2Zoki\nu0Rn3bgMAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADUElEQVRIDcWVS0wTURSG/yktQ9spNLpA4qIl\nMTFoDES3Kk1ciHHRrsToAl9xYVDqE2iMVKKBBMNjJQQTutIgCxs1ASHGURNC3Ahx4UaSRpcueAho\nQBjPOXc6Q4C1nMXMud898//3zJ3eAtsQwd4Tt7bBFujRo0c3GWsdQzEHGu3TMjjWNDaWFar1jeSg\ncFl/p13oQsmI1gAV4ZoEdo3dBUTS0+N9aJcj5snkU7r7zsvAk9AOO7QUwTUevLAsKykVRcBtKJyG\nngBOhQEXSkYPHAEarBVoVzBuQiQLLSsL3zTFFFBiUo0dpW1zkj0FXuYZrgOXefAI0CEVZ4APCvsy\nMKJaUwsZu1AywH8V2N9sQj8HPQ2R9Aw/cWQRR8wd+JXxV6COtFRcBFpilGaB1yRHFW+BnRAcnIRW\nBQxQsQslAz4dAJL0XEkUwVmIpK4U+WrMvmLFfNjGv4GZRJ5VhpUxUNytjGemMArBxavhYEYZu1Ay\nWqhtHJmEfwEiuc5Ya/7ZH85bKFn6EP6QMZk4Ua1KQgR4abo1lOE5wi3Lo5Rwxy5UWcAk49TgAxRS\nx2tKUn/eG+MHN4fq2FgB4ll3tpjGHOwhFe/meSWMg1Y5ZWwMF0pWBjKewuccvWfPspIMhQ35Tql6\nQ9jG1LEYa2q6ICl3bZZuXOG7V32NUsa1P5ZyytiFKsuyMRCqQgXOLhp5yS8MndhxiGPPplcdiUpJ\nuyr084iNn8G/RD0SDiQxQL9A7tiFkvliyrjoLwJ9Jxec3esyldiGq+qYv4S6BE2pVv1pVVUwSXeu\nqKcXkgDjQhPeRWXsQsl2g4x13l56SJ9TkjdoQ3I03hy28TQdF9SEHadhmJxGknShCn7legaMI0RS\nYuzC9zJd29i41EzfVREtFJ4kRPIC0OXq0oQTtjH92lsd5k3Db/IonqaL3XHI9DIuNIFvTsc2pI5D\nxHGVT7OCaKAecZMPkFakgYM0sUWwLG1sQUK75Mx+HBu5yRB1aWJc8T2MQQguLkegWxm7UDIqXYVB\nJ5bpL9f20QJYcgK0iq2i6M58ijdWe/M45sxXWtYv2e3xBJ3IXOFtoj8JwTje0Qm0NezNrIMyTUeZ\nlcLE8H1gpD1HZwNLGh1NW79px+w/Jf8Ai2Q6WOYdK4QAAAAASUVORK5CYII=\n",
"text/latex": [
"$$- 1.0 \\cdot 2.71828182845905^{- x}$$"
],
"text/plain": [
" -x\n",
"-1.0⋅2.71828182845905 "
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sympy.diff(z)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"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.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
week13/.ipynb_checkpoints/Initial-Value-checkpoint.ipynb
0 → 100644
View file @
f7f9d76a
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Optimization\n",
"\n",
"> หาค่า $x$ ที่ทำให้ $F(x)$ มีค่าน้อยที่สุด และทำให้ $g(x) = 0, h(x) \\ge 0$\n",
"\n",
"$F(x)$ - objective function\n",
"\n",
"$x$ - design variable\n",
"\n",
"$g(x), h(x)$ - constraint functions\n",
"\n",
"minimize $F(x)$ = maximize $-F(x)$\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> จงหาค่า $x$ ในช่วง $[a,b]$ ที่ทำ $f(x)$ มีค่าน้อยที่สุด\n",
"\n",
"## Bracketing\n",
"- $x = a$\n",
"- เลือกค่า $x$ ใหม่ ตามทิศทาง $dx = +\\Delta$ หรือ $dx = -\\Delta$ ที่ทำให้ค่า $f(x+dx) \\lt f(x)$\n",
"- กำหนดให้ $x = x + dx$ ไปเรื่อยๆ จนกว่า $f(x+dx) > f(x)$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Golden Section Search\n",
"\n",
"```python\n",
"def search(f,a,b,tol=1.0e-9):\n",
" nIter = int(math.ceil(-2.078087*math.log(tol/abs(b-a))))\n",
" R = 0.618033989\n",
" C = 1.0 - R\n",
" # First telescoping\n",
" x1 = R*a + C*b; x2 = C*a + R*b\n",
" f1 = f(x1); f2 = f(x2)\n",
" # Main loop\n",
" for i in range(nIter):\n",
" if f1 > f2:\n",
" a = x1\n",
" x1 = x2; f1 = f2\n",
" x2 = C*a + R*b; f2 = f(x2)\n",
" else:\n",
" b = x2\n",
" x2 = x1; f2 = f1\n",
" x1 = R*a + C*b; f1 = f(x1)\n",
"\n",
" if f1 < f2: return x1,f1\n",
" return x2,f2\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Powell's Method\n",
"\n",
"* Choose a point $x_0$ in the design space\n",
"* Choose the starting vectors $v_i$ , $i=1, 2, . . . , n$ (the usual choice is $v_i = e_i$ \n",
" * where $e_i$ is the unit vector in the $x_i$ -coordinate direction)\n",
"* Cycle:\n",
" * Loop over $i = 1, 2, . . . , n$:\n",
" * Minimize $F(x)$ along the line through $x_{i−1}$ in the direction of $v_i$\n",
" * Let the minimum point be $x_i$\n",
" * End loop.\n",
" * $v_{n+1} \\leftarrow x_0 − x_n$\n",
" * Minimize $F(x)$ along the line through $x_0$ in the direction of $v_{n+1}$\n",
" * Let the minimum point be $x_{n+1}$\n",
" * if $|x n+1 − x 0 | < ε$ exit loop\n",
" * Loop over $i = 1, 2, . . . , n$\n",
" * $v_i = v_{i+1}$ ($v_1$ is discarded; the other vectors are reused).\n",
" * End loop\n",
" * $x_0 = x_{n+1}$\n",
"* End cycle\n",
"\n",
"\n",
"```python\n",
"import numpy as np\n",
"import math\n",
"\n",
"def powell(F,x,h=0.1,tol=1.0e-6):\n",
"\n",
" def f(s): return F(x + s*v)\n",
"\n",
" n = len(x)\n",
" df = np.zeros(n)\n",
" u = np. identity(n)\n",
"\n",
" for j in range(30):\n",
" xOld = x.copy()\n",
" fOld = F(xOld)\n",
" \n",
" for i in range(n):\n",
" v = u[i]\n",
" a,b = bracket(f,0.0,h)\n",
" s,fMin = search(f,a,b)\n",
" df[i] = fOld - fMin\n",
" fOld = fMin\n",
" x = x + s*v\n",
"\n",
" v = x - xOld\n",
" a,b = bracket(f,0.0,h)\n",
" s,fLast = search(f,a,b)\n",
" x = x + s*v\n",
" if math.sqrt(np.dot(x-xOld,x-xOld)/n) < tol: return x,j+1\n",
" iMax = np.argmax(df)\n",
" for i in range(iMax,n-1):\n",
" u[i] = u[i+1]\n",
" u[n-1] = v\n",
"\n",
" print(\"Powell did not converge\")\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## example\n",
"1. จงเขียนโปรแกรมหา $x$ ที่ทำให้ $f(x) = 100(y-x^2)^2 + (1-x)^2$ ด้วยวิธี Powell โดยเริ่มจากจุด $(-1,1)$\n",
"\n",
"```python\n",
"from numpy import array\n",
"\n",
"def F(x): return 100.0*(x[1] - x[0]**2)**2 + (1 - x[0])**2\n",
"\n",
"xStart = array([-1.0, 1.0])\n",
"xMin,nIter = powell(F,xStart)\n",
"print(\"x =\",xMin)\n",
"print(\"F(x) =\",F(xMin))\n",
"print(\"Number of cycles =\",nIter)\n",
"input (\"Press return to exit\")\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Downhil Simplex Method (Nelder-Mead Method)\n",
"\n",
"* Choose a starting simplex\n",
"* Cycle until $d \\le \\epsilon$ \n",
" * Try reflection\n",
" * if new vertex $\\le$ old $Lo$: accept reflection\n",
" * Try expansion\n",
" * if new vertex $\\le$ old $Lo$: accept expansion\n",
" * else:\n",
" * if new vertex $>$ old $Hi$:\n",
" * Try contraction\n",
" * if new vertex $\\le$ old $Hi$: accept contraction\n",
" * else: use shrinkage\n",
" \n",
" \n",
"```python\n",
"import numpy as np\n",
"import math\n",
"\n",
"def downhill(F,xStart,side=0.1,tol=1.0e-6):\n",
" n = len(xStart)\n",
" x = np.zeros((n+1,n))\n",
" f = np.zeros(n+1)\n",
" x[0] = xStart\n",
" for i in range(1,n+1):\n",
" x[i] = xStart\n",
" x[i,i-1] = xStart[i-1] + side\n",
"\n",
" for i in range(n+1): f[i] = F(x[i])\n",
"\n",
" for k in range(500):\n",
" iLo = np.argmin(f)\n",
" iHi = np.argmax(f)\n",
" d = (-(n+1)*x[iHi] + np.sum(x,axis=0))/n\n",
" if math.sqrt(np.dot(d,d)/n) < tol: return x[iLo]\n",
"\n",
" # Try reflection\n",
" xNew = x[iHi] + 2.0*d\n",
" fNew = F(xNew)\n",
" if fNew <= f[iLo]:\n",
" # Accept reflection\n",
" x[iHi] = xNew\n",
" f[iHi] = fNew\n",
"\n",
" # Try expanding the reflection\n",
" xNew = x[iHi] + d\n",
" fNew = F(xNew)\n",
" if fNew <= f[iLo]:\n",
" # Accept expansion\n",
" x[iHi] = xNew\n",
" f[iHi] = fNew\n",
" else:\n",
" if fNew <= f[iHi]:\n",
" # Accept reflection\n",
" x[iHi] = xNew\n",
" f[iHi] = fNew\n",
" else:\n",
" # Try contraction\n",
" xNew = x[iHi] + 0.5*d\n",
" fNew = F(xNew)\n",
" if fNew <= f[iHi]: # Accept contraction\n",
" x[iHi] = xNew\n",
" f[iHi] = fNew\n",
" else:\n",
" # Use shrinkage\n",
" for i in range(len(x)):\n",
" if i != iLo:395\n",
" x[i] = (x[i] - x[iLo])*0.5\n",
" f[i] = F(x[i])\n",
"\n",
" print(\"Too many iterations in downhill\")\n",
" return x[iLo]\n",
"```"
]
}
],
"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.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
week13/Initial-Value.ipynb
0 → 100644
View file @
f7f9d76a
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Optimization\n",
"\n",
"> หาค่า $x$ ที่ทำให้ $F(x)$ มีค่าน้อยที่สุด และทำให้ $g(x) = 0, h(x) \\ge 0$\n",
"\n",
"$F(x)$ - objective function\n",
"\n",
"$x$ - design variable\n",
"\n",
"$g(x), h(x)$ - constraint functions\n",
"\n",
"minimize $F(x)$ = maximize $-F(x)$\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> จงหาค่า $x$ ในช่วง $[a,b]$ ที่ทำ $f(x)$ มีค่าน้อยที่สุด\n",
"\n",
"## Bracketing\n",
"- $x = a$\n",
"- เลือกค่า $x$ ใหม่ ตามทิศทาง $dx = +\\Delta$ หรือ $dx = -\\Delta$ ที่ทำให้ค่า $f(x+dx) \\lt f(x)$\n",
"- กำหนดให้ $x = x + dx$ ไปเรื่อยๆ จนกว่า $f(x+dx) > f(x)$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Golden Section Search\n",
"\n",
"```python\n",
"def search(f,a,b,tol=1.0e-9):\n",
" nIter = int(math.ceil(-2.078087*math.log(tol/abs(b-a))))\n",
" R = 0.618033989\n",
" C = 1.0 - R\n",
" # First telescoping\n",
" x1 = R*a + C*b; x2 = C*a + R*b\n",
" f1 = f(x1); f2 = f(x2)\n",
" # Main loop\n",
" for i in range(nIter):\n",
" if f1 > f2:\n",
" a = x1\n",
" x1 = x2; f1 = f2\n",
" x2 = C*a + R*b; f2 = f(x2)\n",
" else:\n",
" b = x2\n",
" x2 = x1; f2 = f1\n",
" x1 = R*a + C*b; f1 = f(x1)\n",
"\n",
" if f1 < f2: return x1,f1\n",
" return x2,f2\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Powell's Method\n",
"\n",
"* Choose a point $x_0$ in the design space\n",
"* Choose the starting vectors $v_i$ , $i=1, 2, . . . , n$ (the usual choice is $v_i = e_i$ \n",
" * where $e_i$ is the unit vector in the $x_i$ -coordinate direction)\n",
"* Cycle:\n",
" * Loop over $i = 1, 2, . . . , n$:\n",
" * Minimize $F(x)$ along the line through $x_{i−1}$ in the direction of $v_i$\n",
" * Let the minimum point be $x_i$\n",
" * End loop.\n",
" * $v_{n+1} \\leftarrow x_0 − x_n$\n",
" * Minimize $F(x)$ along the line through $x_0$ in the direction of $v_{n+1}$\n",
" * Let the minimum point be $x_{n+1}$\n",
" * if $|x n+1 − x 0 | < ε$ exit loop\n",
" * Loop over $i = 1, 2, . . . , n$\n",
" * $v_i = v_{i+1}$ ($v_1$ is discarded; the other vectors are reused).\n",
" * End loop\n",
" * $x_0 = x_{n+1}$\n",
"* End cycle\n",
"\n",
"\n",
"```python\n",
"import numpy as np\n",
"import math\n",
"\n",
"def powell(F,x,h=0.1,tol=1.0e-6):\n",
"\n",
" def f(s): return F(x + s*v)\n",
"\n",
" n = len(x)\n",
" df = np.zeros(n)\n",
" u = np. identity(n)\n",
"\n",
" for j in range(30):\n",
" xOld = x.copy()\n",
" fOld = F(xOld)\n",
" \n",
" for i in range(n):\n",
" v = u[i]\n",
" a,b = bracket(f,0.0,h)\n",
" s,fMin = search(f,a,b)\n",
" df[i] = fOld - fMin\n",
" fOld = fMin\n",
" x = x + s*v\n",
"\n",
" v = x - xOld\n",
" a,b = bracket(f,0.0,h)\n",
" s,fLast = search(f,a,b)\n",
" x = x + s*v\n",
" if math.sqrt(np.dot(x-xOld,x-xOld)/n) < tol: return x,j+1\n",
" iMax = np.argmax(df)\n",
" for i in range(iMax,n-1):\n",
" u[i] = u[i+1]\n",
" u[n-1] = v\n",
"\n",
" print(\"Powell did not converge\")\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## example\n",
"1. จงเขียนโปรแกรมหา $x$ ที่ทำให้ $f(x) = 100(y-x^2)^2 + (1-x)^2$ ด้วยวิธี Powell โดยเริ่มจากจุด $(-1,1)$\n",
"\n",
"```python\n",
"from numpy import array\n",
"\n",
"def F(x): return 100.0*(x[1] - x[0]**2)**2 + (1 - x[0])**2\n",
"\n",
"xStart = array([-1.0, 1.0])\n",
"xMin,nIter = powell(F,xStart)\n",
"print(\"x =\",xMin)\n",
"print(\"F(x) =\",F(xMin))\n",
"print(\"Number of cycles =\",nIter)\n",
"input (\"Press return to exit\")\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Downhil Simplex Method (Nelder-Mead Method)\n",
"\n",
"* Choose a starting simplex\n",
"* Cycle until $d \\le \\epsilon$ \n",
" * Try reflection\n",
" * if new vertex $\\le$ old $Lo$: accept reflection\n",
" * Try expansion\n",
" * if new vertex $\\le$ old $Lo$: accept expansion\n",
" * else:\n",
" * if new vertex $>$ old $Hi$:\n",
" * Try contraction\n",
" * if new vertex $\\le$ old $Hi$: accept contraction\n",
" * else: use shrinkage\n",
" \n",
" \n",
"```python\n",
"import numpy as np\n",
"import math\n",
"\n",
"def downhill(F,xStart,side=0.1,tol=1.0e-6):\n",
" n = len(xStart)\n",
" x = np.zeros((n+1,n))\n",
" f = np.zeros(n+1)\n",
" x[0] = xStart\n",
" for i in range(1,n+1):\n",
" x[i] = xStart\n",
" x[i,i-1] = xStart[i-1] + side\n",
"\n",
" for i in range(n+1): f[i] = F(x[i])\n",
"\n",
" for k in range(500):\n",
" iLo = np.argmin(f)\n",
" iHi = np.argmax(f)\n",
" d = (-(n+1)*x[iHi] + np.sum(x,axis=0))/n\n",
" if math.sqrt(np.dot(d,d)/n) < tol: return x[iLo]\n",
"\n",
" # Try reflection\n",
" xNew = x[iHi] + 2.0*d\n",
" fNew = F(xNew)\n",
" if fNew <= f[iLo]:\n",
" # Accept reflection\n",
" x[iHi] = xNew\n",
" f[iHi] = fNew\n",
"\n",
" # Try expanding the reflection\n",
" xNew = x[iHi] + d\n",
" fNew = F(xNew)\n",
" if fNew <= f[iLo]:\n",
" # Accept expansion\n",
" x[iHi] = xNew\n",
" f[iHi] = fNew\n",
" else:\n",
" if fNew <= f[iHi]:\n",
" # Accept reflection\n",
" x[iHi] = xNew\n",
" f[iHi] = fNew\n",
" else:\n",
" # Try contraction\n",
" xNew = x[iHi] + 0.5*d\n",
" fNew = F(xNew)\n",
" if fNew <= f[iHi]: # Accept contraction\n",
" x[iHi] = xNew\n",
" f[iHi] = fNew\n",
" else:\n",
" # Use shrinkage\n",
" for i in range(len(x)):\n",
" if i != iLo:395\n",
" x[i] = (x[i] - x[iLo])*0.5\n",
" f[i] = F(x[i])\n",
"\n",
" print(\"Too many iterations in downhill\")\n",
" return x[iLo]\n",
"```"
]
}
],
"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.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment