{"id":1955,"date":"2023-08-27T06:26:08","date_gmt":"2023-08-27T13:26:08","guid":{"rendered":"https:\/\/gantovnik.com\/bio-tips\/?p=1955"},"modified":"2023-08-27T06:26:08","modified_gmt":"2023-08-27T13:26:08","slug":"389-calculating-pi-with-monte-carlo-simulation","status":"publish","type":"post","link":"https:\/\/gantovnik.com\/bio-tips\/2023\/08\/389-calculating-pi-with-monte-carlo-simulation\/","title":{"rendered":"#389 Calculating pi with Monte Carlo Simulation"},"content":{"rendered":"<p><a href=\"https:\/\/gantovnik.com\/bio-tips\/2023\/08\/389-calculating-pi-with-monte-carlo-simulation\/ex389_1\/\" rel=\"attachment wp-att-1956\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/08\/ex389_1.png?resize=600%2C600&#038;ssl=1\" alt=\"\" width=\"600\" height=\"600\" class=\"alignnone size-full wp-image-1956\" srcset=\"https:\/\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/08\/ex389_1.png 600w, https:\/\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/08\/ex389_1-480x480.png 480w\" sizes=\"(min-width: 0px) and (max-width: 480px) 480px, (min-width: 481px) 600px, 100vw\" \/><\/a><\/p>\n<p><a href=\"https:\/\/gantovnik.com\/bio-tips\/2023\/08\/389-calculating-pi-with-monte-carlo-simulation\/ex389_2\/\" rel=\"attachment wp-att-1957\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/08\/ex389_2.png?resize=1080%2C540&#038;ssl=1\" alt=\"\" width=\"1080\" height=\"540\" class=\"alignnone size-full wp-image-1957\" srcset=\"https:\/\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/08\/ex389_2.png 1200w, https:\/\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/08\/ex389_2-980x490.png 980w, https:\/\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/08\/ex389_2-480x240.png 480w\" sizes=\"(min-width: 0px) and (max-width: 480px) 480px, (min-width: 481px) and (max-width: 980px) 980px, (min-width: 981px) 1200px, 100vw\" \/><\/a><\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n# Calculating pi with Monte Carlo Simulation\r\nimport random\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nrandom.seed(2021)\r\npi_values = list()\r\nnum_experiments = 1000\r\nnum_rounds = 20\r\nnum_points = 1000\r\nedge = 10\r\nfor r in range(num_rounds):\r\n    for p in range(num_experiments):\r\n        in_circle = 0\r\n        for g in range(num_points):\r\n            x, y = (random.random() - 0.5)*edge, (random.random() - 0.5)*edge\r\n            if x**2 + y**2 &lt;= (edge\/2)**2:\r\n                in_circle = in_circle + 1\r\n        pi = in_circle\/num_points * 4\r\n        pi_values.append(pi)\r\nprint(np.mean(pi_values),np.pi)        \r\n\r\nrandom.seed(2021)\r\nedge = 10\r\nnum_points = 1000\r\nwith plt.xkcd():\r\n    fig, ax = plt.subplots(figsize=(6, 6))\r\n# plt.axis(&quot;off&quot;)\r\n    plt.axis(&quot;equal&quot;)\r\n    ax.set_xlim(-edge\/2, edge\/2)\r\n    ax.set_ylim(-edge\/2, edge\/2)\r\n    xs_in, ys_in = list(), list()\r\n    xs_out, ys_out = list(), list()\r\n    for g in range(num_points):\r\n        x, y = (random.random() - 0.5)*edge, (random.random() - 0.5)*edge\r\n        if x**2 + y**2 &lt;= (edge\/2)**2:\r\n            xs_in.append(x)\r\n            ys_in.append(y)\r\n        else:\r\n            xs_out.append(x)\r\n            ys_out.append(y)\r\n    ax.scatter(xs_in, ys_in, color=&quot;r&quot;)\r\n    ax.scatter(xs_out, ys_out, color=&quot;b&quot;)\r\n    circle = plt.Circle((0, 0), edge\/2, fill=False, color=&quot;g&quot;, lw=3)\r\n    ax.add_patch(circle)\r\n    ax.set_title(&quot;An experiment with 1000 points&quot;, fontsize=20)\r\n    plt.savefig(&quot;ex389_1.png&quot;, dpi=100)\r\n    plt.show()\r\n    \r\n    \r\nwith plt.xkcd():\r\n    fig, ax = plt.subplots(figsize=(12, 6))\r\n    ax.hist(pi_values, bins=50, rwidth=0.8)\r\n    pi_mean = np.mean(pi_values)\r\n    pi_median = np.median(pi_values)\r\n    # pi_mean and pi_median are very close.\r\n    \r\n    pi_std = np.std(pi_values)\r\n    pi_quartiles = np.quantile(pi_values, &#x5B;0, 0.25, 0.5, 0.75, 1])\r\n    ax.set_title(\r\n        &quot;Statistics of the Experiments&quot;, fontsize=20)\r\n    line_1 = ax.axvline(pi_mean, color='red', lw=1)\r\n    line_2 = ax.axvline(pi_quartiles&#x5B;1],\r\n                        color='purple',\r\n                        lw=3,\r\n                        linestyle=&quot;dotted&quot;)\r\n    line_3 = ax.axvline(pi_quartiles&#x5B;3],\r\n                        color='green',\r\n                        lw=3,\r\n                        linestyle=&quot;dashed&quot;)\r\n    std_bar = ax.errorbar(pi_mean, 1200,\r\n                          xerr=pi_std,\r\n                          capsize=5,\r\n                          elinewidth=3,\r\n                          markeredgewidth=2,\r\n                          linestyle=&quot;:&quot;)\r\n    ax.legend(&#x5B;line_1, line_2, line_3, std_bar],\r\n              &#x5B;&quot;median = {}&quot;.format(pi_median),\r\n               &quot;first quartile = {}&quot;.format(pi_quartiles&#x5B;1]),\r\n               &quot;third quartile = {}&quot;.format(pi_quartiles&#x5B;3]),\r\n               &quot;standard deviation =\\n {}&quot;.format(round(pi_std, 4))],\r\n              fontsize=18)    \r\n    plt.savefig(&quot;ex389_2.png&quot;, dpi=100)\r\n    plt.show()  \r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p># Calculating pi with Monte Carlo Simulation import random import numpy as np import matplotlib.pyplot as plt random.seed(2021) pi_values = list() num_experiments = 1000 num_rounds = 20 num_points = 1000 edge = 10 for r in range(num_rounds): for p in range(num_experiments): in_circle = 0 for g in range(num_points): x, y = (random.random() &#8211; 0.5)*edge, (random.random() [&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":[69,93,2],"tags":[],"class_list":["post-1955","post","type-post","status-publish","format-standard","hentry","category-matplotlib","category-monte-carlo","category-python"],"modified_by":"gantovnik","jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p8bH0k-vx","jetpack_likes_enabled":true,"jetpack-related-posts":[{"id":3022,"url":"https:\/\/gantovnik.com\/bio-tips\/2024\/07\/442-the-partial-sums-of-the-fourier-series-for-the-square-wave-function-using-python\/","url_meta":{"origin":1955,"position":0},"title":"#442 The partial sums of the Fourier series for the square-wave function using python","author":"gantovnik","date":"2024-07-25","format":false,"excerpt":"import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider nmax = 5 pi = np.pi x = np.linspace(-2*pi, 2*pi, 1001) def f(xarray): y = np.zeros_like(xarray) for ind, x in enumerate(xarray): xmod = x%(2*pi) if xmod<pi: y[ind] = 1 if x%pi==0: y[ind]= np.nan return y def Fourier(x, nmax):\u2026","rel":"","context":"In &quot;animation&quot;","block_context":{"text":"animation","link":"https:\/\/gantovnik.com\/bio-tips\/category\/animation\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/07\/ex442_3.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/07\/ex442_3.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/07\/ex442_3.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":365,"url":"https:\/\/gantovnik.com\/bio-tips\/2019\/01\/solution-of-laplace-equation-using-fem\/","url_meta":{"origin":1955,"position":1},"title":"#51 Solution of Laplace equation using FEM","author":"gantovnik","date":"2019-01-29","format":false,"excerpt":"[code language=\"python\"] import os import matplotlib.pyplot as plt import numpy as np from numpy import linspace from scipy.spatial import Delaunay from numpy import cross from scipy.sparse import dok_matrix import matplotlib.cm as cm os.chdir(r'D:\\projects\\wordpress\\ex51') os.getcwd() xmin = 0 ; xmax = 1 ; nXpoints = 10 ymin = 0 ; ymax\u2026","rel":"","context":"In &quot;fem&quot;","block_context":{"text":"fem","link":"https:\/\/gantovnik.com\/bio-tips\/category\/fem\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example61_3.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example61_3.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2019\/01\/example61_3.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":1179,"url":"https:\/\/gantovnik.com\/bio-tips\/2021\/11\/204-mandelbrot-fractal-using-python-2\/","url_meta":{"origin":1955,"position":2},"title":"#205 Plots with annotation in matplotlib","author":"gantovnik","date":"2021-11-26","format":false,"excerpt":"[code language=\"python\"] import numpy as np import matplotlib.pyplot as plt plt.fig = plt.figure(1) plt.ax = plt.subplot(111) x = np.linspace(0,2*np.pi,100) # Function that modulates the amplitude of the sin function amod_sin = lambda x: (1.-0.1*np.sin(25*x))*np.sin(x) plt.ax.plot(x,np.sin(x),label = 'sin') plt.ax.plot(x, amod_sin(x), label = 'modsin') annot1=plt.ax.annotate('amplitude modulated\\n curve', (2.1,1.0), (3.2,0.5), arrowprops={'width':2,'color':'k','connectionstyle':'arc3,rad=+0.5','shrink':0.05},verticalalignment='bottom', horizontalalignment='left', fontsize=10,\u2026","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\/ex205.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1758,"url":"https:\/\/gantovnik.com\/bio-tips\/2023\/01\/335-solution-of-nonlinear-equation-using-brent-method-in-python\/","url_meta":{"origin":1955,"position":3},"title":"#335 Solution of nonlinear equation by Brent&#8217;s method in python","author":"gantovnik","date":"2023-01-06","format":false,"excerpt":"Brent's method is a hybrid root-finding algorithm combining the bisection method, the secant method, and inverse quadratic interpolation. ex335.py [code language=\"python\"] import numpy as np import matplotlib.pyplot as plt import scipy.optimize as optimize def f(x): return 2*x - 1 + 2*np.cos(np.pi*x) x = np.linspace(0.0,2.0,201) y=f(x) plt.plot(x,y,label='$2x - 1 + 2\\\\cos(\\\\pi\u2026","rel":"","context":"In &quot;optimization&quot;","block_context":{"text":"optimization","link":"https:\/\/gantovnik.com\/bio-tips\/category\/optimization\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2023\/01\/ex335.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":2140,"url":"https:\/\/gantovnik.com\/bio-tips\/2024\/02\/417-polar-plot-using-sympy-plotting-functions-in-python\/","url_meta":{"origin":1955,"position":4},"title":"#417 Polar plot using SymPy plotting functions in python","author":"gantovnik","date":"2024-02-21","format":false,"excerpt":"[code language=\"python\"] import matplotlib.pyplot as plt from sympy import symbols, sin, cos, pi, latex from spb import plot_polar x = symbols(\"x\") expr = sin(2 * x) * cos(5 * x) + pi \/ 2 plot_polar(expr, (x, 0, 2 * pi), polar_axis=True, ylim=(0, 3), title=\"$%s$\" % latex(expr)) plt.savefig(\"ex417.png\", dpi=100) plt.show() [\/code]","rel":"","context":"In &quot;matplotlib&quot;","block_context":{"text":"matplotlib","link":"https:\/\/gantovnik.com\/bio-tips\/category\/matplotlib\/"},"img":{"alt_text":"","src":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/02\/ex417.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/02\/ex417.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/02\/ex417.png?resize=525%2C300&ssl=1 1.5x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2024\/02\/ex417.png?resize=700%2C400&ssl=1 2x"},"classes":[]},{"id":1718,"url":"https:\/\/gantovnik.com\/bio-tips\/2022\/12\/204-mandelbrot-fractal-using-python-2-2-2-2-2-2\/","url_meta":{"origin":1955,"position":5},"title":"#325 Finding the intersection points between two functions using python","author":"gantovnik","date":"2022-12-13","format":false,"excerpt":"[code language=\"python\"] from scipy.optimize import fsolve import numpy as np import matplotlib.pyplot as plt # Defining function to simplify intersection solution def findIntersection(func1, func2, x0): return fsolve(lambda x : func1(x) - func2(x), x0) # Defining functions that will intersect funky = lambda x : np.cos(x \/ 5) * np.sin(x \/\u2026","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\/2022\/12\/ex325.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2022\/12\/ex325.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/gantovnik.com\/bio-tips\/wp-content\/uploads\/2022\/12\/ex325.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]}],"_links":{"self":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/1955","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=1955"}],"version-history":[{"count":0,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/posts\/1955\/revisions"}],"wp:attachment":[{"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/media?parent=1955"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/categories?post=1955"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/gantovnik.com\/bio-tips\/wp-json\/wp\/v2\/tags?post=1955"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}