+{"cells":[{"cell_type":"markdown","metadata":{"id":"Brtl6ZgJqgu2"},"source":["# COURSE: Master math by coding in Python\n","# SECTION: Number theory\n","# VIDEO: Heron's method of square roots\n","\n","\n","### https://www.udemy.com/course/math-with-python/?couponCode=202312\n","#### INSTRUCTOR: Mike X Cohen (http://sincxpress.com)\n","\n","This code roughly matches the code shown in the live recording: variable names, order of lines, and parameter settings may be slightly different."]},{"cell_type":"markdown","source":["<a target=\"_blank\" href=\"https://colab.research.google.com/github/mikexcohen/MathWithPython/blob/main/numberTheory/mathWithPython_numTheory_HeronRoots.ipynb\">\n"," <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n","</a>"],"metadata":{"id":"JZhUk_36xwBy"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"JL_0UKJOj1YP"},"outputs":[],"source":["# import libraries\n","import numpy as np\n","import matplotlib.pyplot as plt\n","import sympy as sym"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"k1RUmn8tOKPi"},"outputs":[],"source":["# Let's test the algorithm in a simple example\n","num = 100\n","\n","# initialze the first guess\n","x = num/3\n","\n","# now run through the algorithm\n","for n in range(5):\n"," x = ( x + num/x )/2\n"," print(x)\n","\n","x"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"CJXd06MIRn0d"},"outputs":[],"source":["# define the numbers to compute\n","nums2sqrt = np.linspace(2,101,50)\n","\n","# range of algorithm iterations\n","niterations = np.arange(3,9)\n","\n","\n","# initialize matrix of estimates\n","err = np.zeros((len(niterations),len(nums2sqrt)))\n","\n","\n","# loop over the numbers to compute\n","for ni,num in enumerate(nums2sqrt):\n","\n"," # loop over number of iterations\n"," for ii,iters in enumerate(niterations):\n","\n"," # initial guess\n"," x = num/3\n","\n"," # implement algorithm\n"," for n in range(iters):\n"," x = ( x + num/x )/2\n","\n"," # store error magnitude\n"," err[ii,ni] = abs(x-np.sqrt(num))\n"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"uOQCIiLygR7C"},"outputs":[],"source":["plt.imshow(-np.log(err),aspect=10,extent=[nums2sqrt[0],nums2sqrt[-1],niterations[-1],niterations[0]])\n","plt.xlabel('Number')\n","plt.ylabel('Iterations')\n","plt.title('-log(error)')\n","plt.show()"]},{"cell_type":"code","source":[],"metadata":{"id":"1ry75mB0pFJp"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"kOLHbqhrKxb-"},"source":["# Exercise"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"qig6omyHHtgW"},"outputs":[],"source":["# Exercise: Heron's mosquito space ship #13\n","# select target number to compute square root of\n","targnum = 13\n","\n","# range of starting values\n","starting = np.linspace(-targnum,targnum,40)\n","\n","# number of iterations (fixed)\n","niters = 5\n","\n","# initialize output matrix\n","sqrtAlgResults = np.zeros((len(starting),niters+1))\n","\n","\n","# loop over starting numbers\n","for idx,startnum in enumerate(starting):\n","\n"," # initialize starting number as a list!\n"," x = [startnum]\n","\n"," # now run through the algorithm\n"," for n in range(niters):\n"," betterguess = ( x[n] + targnum/x[n] )/2\n"," x.append( betterguess )\n","\n"," sqrtAlgResults[idx,:] = x\n","\n","\n","# finally, plot the results\n","fig,ax = plt.subplots(1,figsize=(8,6))\n","plt.plot(np.arange(niters+1),sqrtAlgResults.T,linewidth=2)\n","plt.xlabel('Algorithm iteration')\n","plt.ylabel('Numerical approximation')\n","plt.title('Estimating $\\sqrt{%g}$ = %g' %(targnum,sqrtAlgResults[-1,-1]))\n","plt.show()"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"d0G3dj1jHtgX"},"outputs":[],"source":[]}],"metadata":{"colab":{"provenance":[]},"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.3"}},"nbformat":4,"nbformat_minor":0}
0 commit comments