{"id":96,"date":"2018-12-31T06:54:32","date_gmt":"2018-12-31T06:54:32","guid":{"rendered":"http:\/\/gantovnik.com\/bio-tips\/?p=96"},"modified":"2024-06-26T04:07:59","modified_gmt":"2024-06-26T11:07:59","slug":"bisection-method","status":"publish","type":"post","link":"https:\/\/gantovnik.com\/bio-tips\/2018\/12\/bisection-method\/","title":{"rendered":"#16 Bisection method using python"},"content":{"rendered":"<p><img data-recalc-dims=\"1\" decoding=\"async\" class=\"  wp-image-97 aligncenter\" src=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example16.png?resize=583%2C194\" alt=\"example16\" width=\"583\" height=\"194\" srcset=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example16.png?w=1200&amp;ssl=1 1200w, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example16.png?resize=300%2C100&amp;ssl=1 300w, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example16.png?resize=768%2C256&amp;ssl=1 768w, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example16.png?resize=1024%2C341&amp;ssl=1 1024w\" sizes=\"(max-width: 583px) 100vw, 583px\" \/><\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nos.chdir(&#039;\/home\/vg\/Downloads\/projects\/ex16&#039;)\r\nos.getcwd()\r\nf = lambda x: np.exp(x)-2\r\ntol=0.1\r\na,b=-2,2\r\nx=np.linspace(-2.1,2.1,1000)\r\nfig,ax=plt.subplots(1,1,figsize=(12,4)) \r\nax.plot(x,f(x),lw=1.5)\r\nax.axhline(0,ls=&#039;:&#039;,color=&#039;k&#039;)\r\nax.set_xticks(&#x5B;-2,-1,0,1,2])\r\nax.set_xlabel(r&#039;$x$&#039;,fontsize=18)\r\nax.set_ylabel(r&#039;$f(x)$&#039;,fontsize=18)\r\nfa,fb=f(a),f(b)\r\nax.plot(a,fa,&#039;ko&#039;)\r\nax.plot(b,fb,&#039;ko&#039;)\r\nax.text(a,fa+0.5,r&quot;$a$&quot;,ha=&#039;center&#039;,fontsize=18)\r\nax.text(b,fb+0.5,r&quot;$b$&quot;,ha=&#039;center&#039;,fontsize=18)\r\nn=1\r\nwhile b-a &amp;gt; tol:\r\n    m=a+(b-a)\/2\r\n    fm=f(m)\r\n    ax.plot(m,fm,&#039;ko&#039;)\r\n    ax.text(m,fm-0.5,r&quot;$m_%d$&quot; % n,ha=&#039;center&#039;)\r\n    n=n+1\r\n    if (np.sign(fa)==np.sign(fm)):\r\n        a,fa=m,fm\r\n    else:\r\n        b,fb=m,fm\r\n\r\nax.plot(m,fm,&#039;r*&#039;,markersize=10)\r\nax.annotate(&quot;Root approximately at %.3f&quot; % m,fontsize=12,\r\n    xy=(a,fm),xycoords=&#039;data&#039;,\r\n    xytext=(-150,+50),textcoords=&#039;offset points&#039;,\r\n    arrowprops=dict(arrowstyle=&quot;-&amp;gt;&quot;,\r\n    connectionstyle=&quot;arc3, rad=-.5&quot;))\r\nax.set_title(&quot;Bisection method&quot;)\r\nplt.savefig(&quot;example16.png&quot;, dpi=100)\r\nplt.show()\r\nplt.close()\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>import os import matplotlib.pyplot as plt import numpy as np os.chdir(&#039;\/home\/vg\/Downloads\/projects\/ex16&#039;) os.getcwd() f = lambda x: np.exp(x)-2 tol=0.1 a,b=-2,2 x=np.linspace(-2.1,2.1,1000) fig,ax=plt.subplots(1,1,figsize=(12,4)) ax.plot(x,f(x),lw=1.5) ax.axhline(0,ls=&#039;:&#039;,color=&#039;k&#039;) ax.set_xticks(&#x5B;-2,-1,0,1,2]) ax.set_xlabel(r&#039;$x$&#039;,fontsize=18) ax.set_ylabel(r&#039;$f(x)$&#039;,fontsize=18) fa,fb=f(a),f(b) ax.plot(a,fa,&#039;ko&#039;) ax.plot(b,fb,&#039;ko&#039;) ax.text(a,fa+0.5,r&quot;$a$&quot;,ha=&#039;center&#039;,fontsize=18) ax.text(b,fb+0.5,r&quot;$b$&quot;,ha=&#039;center&#039;,fontsize=18) n=1 while b-a &amp;gt; tol: m=a+(b-a)\/2 fm=f(m) ax.plot(m,fm,&#039;ko&#039;) ax.text(m,fm-0.5,r&quot;$m_%d$&quot; % n,ha=&#039;center&#039;) n=n+1 if (np.sign(fa)==np.sign(fm)): a,fa=m,fm else: b,fb=m,fm ax.plot(m,fm,&#039;r*&#039;,markersize=10) ax.annotate(&quot;Root approximately at %.3f&quot; % m,fontsize=12, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","_lmt_disableupdate":"yes","_lmt_disable":"","jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[9,2],"tags":[118,25,3],"class_list":["post-96","post","type-post","status-publish","format-standard","hentry","category-optimization","category-python","tag-bisection","tag-optimization","tag-python"],"modified_by":"gantovnik","jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8bH0k-1y","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":88,"url":"https:\/\/gantovnik.com\/bio-tips\/2018\/12\/linear-least-square-fit\/","url_meta":{"origin":96,"position":0},"title":"#14 Linear least square fit using python","author":"gantovnik","date":"2018-12-31","format":false,"excerpt":"[code language=\"python\"] import os import matplotlib.pyplot as plt import numpy as np import scipy.linalg as la os.chdir('\/home\/vg\/Downloads\/projects\/ex14') os.getcwd() #define model parameters x=np.linspace(-1,1,200) a,b,c=1,2,3 y_exact=a+b*x+c*x**2 #simulate noisy data m=200 X=1-2*np.random.rand(m) Y=a+b*X+c*X**2+np.random.randn(m) #linear least square fit A=np.vstack([X**0,X**1,X**2]) sol,r,rank,sv=la.lstsq(A.T,Y) y_fit=sol[0]+sol[1]*x+sol[2]*x**2 fig,ax=plt.subplots(figsize=(12,4)) ax.plot(X,Y,'go',alpha=0.5,label='simulated data') ax.plot(x,y_exact,'k',lw=2,label='true value $y=1+2x+3x^2$') ax.plot(x,y_fit,'b',lw=2,label='least square fit') #1st order polynomial A=np.vstack([X**n\u2026","rel":"","context":"In &quot;matplotlib&quot;","block_context":{"text":"matplotlib","link":"https:\/\/gantovnik.com\/bio-tips\/category\/matplotlib\/"},"img":{"alt_text":"example13","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example13-1.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example13-1.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2018\/12\/example13-1.png?resize=525%2C300 1.5x"},"classes":[]},{"id":1218,"url":"https:\/\/gantovnik.com\/bio-tips\/2021\/11\/210-parametric-curve-in-3d-2-2-2-2-2-2\/","url_meta":{"origin":96,"position":1},"title":"#216 Mathtext Latex parser in matplotlib","author":"gantovnik","date":"2021-11-28","format":false,"excerpt":"[code language=\"python\"] import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], label=r'$\\sqrt{x^2}$') ax.legend() ax.set_xlabel(r'$\\Delta_i^j$', fontsize=20) ax.set_ylabel(r'$\\Delta_{i+1}^j$', fontsize=20) ax.set_title(r'$\\Delta_i^j \\hspace{0.4} \\mathrm{versus} \\hspace{0.4} ' r'\\Delta_{i+1}^j$', fontsize=20) tex = r'$\\mathcal{R}\\prod_{i=\\alpha_{i+1}}^\\infty a_i\\sin(2 \\pi f x_i)$' ax.text(1, 1.6, tex, fontsize=20, va='bottom') fig.tight_layout() plt.savefig('ex216.png', dpi=72) plt.show() [\/code]","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2021\/11\/ex216.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":495,"url":"https:\/\/gantovnik.com\/bio-tips\/2020\/05\/optimization-with-constraints\/","url_meta":{"origin":96,"position":2},"title":"#72 Optimization with constraints using scipy in python","author":"gantovnik","date":"2020-05-03","format":false,"excerpt":"[code language=\"python\"] import os from scipy.optimize import minimize import matplotlib.pyplot as plt import numpy as np os.chdir(r'D:\\projects\\wordpress\\ex72') os.getcwd() def f(X): x, y = X return (x - 1)2 + (y - 1)2 def func_X_Y_to_XY(f, X, Y): #Wrapper for f(X, Y) -> f([X, Y]) s = np.shape(X) return f(np.vstack([X.ravel(), Y.ravel()])).reshape(*s) x_opt\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"ex72","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2020\/05\/ex72.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2020\/05\/ex72.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2020\/05\/ex72.png?resize=525%2C300 1.5x"},"classes":[]},{"id":130,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/spline-interpolation-2\/","url_meta":{"origin":96,"position":3},"title":"Spline interpolation","author":"gantovnik","date":"2019-01-03","format":false,"excerpt":"import os import matplotlib.pyplot as plt import numpy as np from scipy import interpolate os.chdir(r'D:\\data\\scripts\\web1\\ex26') os.getcwd() def runge(x): return 1\/(1 + 25 * x**2) x = np.linspace(-1, 1, 11) y = runge(x) f = interpolate.interp1d(x, y, kind=3) xx = np.linspace(-1, 1, 100) fig, ax = plt.subplots(figsize=(8, 4)) ax.plot(xx, runge(xx), 'k',\u2026","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"example26","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example26.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example26.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example26.png?resize=525%2C300 1.5x"},"classes":[]},{"id":157,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/numerical-integration-of-odes-using-scipy\/","url_meta":{"origin":96,"position":4},"title":"Numerical integration of ODEs using SciPy","author":"gantovnik","date":"2019-01-09","format":false,"excerpt":"import os import numpy as np import matplotlib.pyplot as plt from scipy import integrate import sympy os.chdir(r'D:\\projects\\wordpress\\ex35') os.getcwd() def plot_direction_field(x, y_x, f_xy, x_lim=(-5, 5), y_lim=(-5, 5), ax=None): f_np = sympy.lambdify((x, y_x), f_xy, 'numpy') x_vec = np.linspace(x_lim[0], x_lim[1], 20) y_vec = np.linspace(y_lim[0], y_lim[1], 20) if ax is None: _, ax =\u2026","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"example35","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example35.png?resize=350%2C200","width":350,"height":200},"classes":[]},{"id":127,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/runge-problem\/","url_meta":{"origin":96,"position":5},"title":"Runge problem","author":"gantovnik","date":"2019-01-03","format":false,"excerpt":"import os import matplotlib.pyplot as plt import numpy as np from numpy import polynomial as P os.chdir(r'D:\\data\\scripts\\web1\\ex25') os.getcwd() # In the mathematical field of numerical analysis, Runge's phenomenon # is a problem of oscillation at the edges of an interval that occurs # when using polynomial interpolation with polynomials of\u2026","rel":"","context":"In &quot;python&quot;","block_context":{"text":"python","link":"https:\/\/gantovnik.com\/bio-tips\/category\/python\/"},"img":{"alt_text":"example25","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example25.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example25.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example25.png?resize=525%2C300 1.5x"},"classes":[]}],"_links":{"self":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/96","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/comments?post=96"}],"version-history":[{"count":2,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/96\/revisions"}],"predecessor-version":[{"id":2228,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/96\/revisions\/2228"}],"wp:attachment":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/media?parent=96"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/categories?post=96"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/tags?post=96"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}