my notes on my code examples<\/a>. That being said, have fun!<\/p>\n\n\n\n#!\/usr\/bin\/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 25 05:52:47 2019\n\nNewton-Raphson method code. \nSolves the method for a given initial guess \nas well as tests the entire x grid as initial guesses\nProduces three figures:\n function overview\n tangents for chosen initial guess\n efficiency of other initial guesses\nIncludes several presets for function, but is easily extendable\n\n@author: Andreas Krassnigg, ComputingSkillSet.com\/about\/\n\nThis work is licensed under a \nCreative Commons Attribution-ShareAlike 4.0 International License.\nMore information: https:\/\/creativecommons.org\/licenses\/by-sa\/4.0\/\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# function definitions to evaluate f and f' at x. Add your own as needed.\n\n# define the function and its derivative to investigate: \n# Demo function\ndef f(x):\n valf = np.sin(x**2) - x**3 - 1\n valdf = 2*x*np.cos(x**2) - 3*x**2\n return (valf, valdf)\n\n# example 1: square root of two\ndef e1(x):\n valf = x**2 - 2\n valdf = 2*x\n return (valf, valdf)\n\n# example 2: cube root of two\ndef e2(x):\n valf = x**3 - 2\n valdf = 3*x**2\n return (valf, valdf)\n\n# example 3: seventh root of seven\ndef e3(x):\n valf = x**7 - 7\n valdf = 7*x**6\n return (valf, valdf)\n\n# example 4: function without roots\ndef e4(x):\n valf = x**2 + 2\n valdf = 2*x\n return (valf, valdf)\n\n# example 5: function with asymptotic region\ndef e5(x):\n valf = x*np.exp(-x) \n valdf = -x*np.exp(-x) + np.exp(-x)\n return (valf, valdf)\n\n# example 6: function with oscillation\ndef e6(x):\n valf = -np.cos(np.absolute(x)+np.pi\/4) + 0.8\n valdf = np.sin(np.absolute(x)+np.pi\/4)*np.sign(x) \n return (valf, valdf)\n\n# example 8: arctangent\ndef e8(x):\n valf = np.arctan(x) \n valdf = 1\/(x**2+1) \n return (valf, valdf)\n\n# example 9: function with many roots\ndef e9(x):\n valf = (x+2)*(x+1.5)*(x-0.5)*(x-2) \n valdf = (x+1.5)*(x-0.5)*(x-2) + (x+2)*(x-0.5)*(x-2) +(x+2)*(x+1.5)*(x-2) + (x+2)*(x+1.5)*(x-0.5) \n return (valf, valdf)\n\n# example 11: function with many roots, one multiple\ndef e11(x):\n valf = (x+2)*(x+1.5)**2*(x-0.5)*(x-2) \n valdf = (x+1.5)**2*(x-0.5)*(x-2) + 2*(x+2)*(x+1.5)*(x-0.5)*(x-2) +(x+2)*(x+1.5)**2*(x-2) + (x+2)*(x+1.5)**2*(x-0.5) \n return (valf, valdf)\n\n\n\n\n# define parameters for plotting - adjust these as needed for your function\n \n# define left and right boundaries for plotting \n# for overview plots:\ninterval_left = -2.1\ninterval_right = 2.1\ninterval_down = -25\ninterval_up = 60\n\n# for search plot:\ninterval_left_search = -2.1\ninterval_right_search = -0.7\ninterval_down_search = -0.2\ninterval_up_search = 2\n\n# set number of points on x axis for plotting and initial-guess analysis\nnum_x = 1000\n\n# define the one initial guess you want to use to get a solution\nchosenx0 = -1\n\n# set desired precision and max number of iterations\nprec_goal = 1.e-10\nnmax = 100\n\n\n# the following defines function to solve and plot. Jump to end of code to choose function\n\n\n# define x grid of points for computation and plotting the function\nxvals = np.linspace(interval_left, interval_right, num=num_x)\n\n# create a list of startin points for Newton's method to loop over later in the code\n# we'll try all x values as starting points\npointlist = xvals\n\ndef solve_and_plot_newton(func):\n \n # begin plotting figure 1: search process with tangents\n plt.figure()\n \n # plot the function f and its derivative\n #fx, dfx = f(xvals)\n fx, dfx = func(xvals)\n plt.plot(xvals, fx, label='$f(x)$')\n # plot the zero line for easy reference\n plt.hlines(0, interval_left, interval_right)\n \n \n # set limits for the x and y axes in the figure\n # set x limits\n plt.xlim((interval_left_search, interval_right_search))\n # set y limits\n plt.ylim((interval_down_search, interval_up_search))\n\n #label the axes\n plt.xlabel(\"$x$\", fontsize=16)\n\n # initialize values for iteration loop\n reldiff = 1\n xi = chosenx0\n counter = 0\n \n print('Starting Newton method at x0 =',chosenx0)\n # start iteration loop\n while reldiff > prec_goal and counter < nmax:\n\n # do the necessary computations\n # get function value and derivative\n fxi, dfxi = func(xi)\n # compute relative difference\n reldiff = np.abs(fxi\/dfxi\/xi)\n # compute next xi\n x1 = xi - fxi\/dfxi\n # print numbers for use in convergence tables (csv format)\n print('%i, %15.12f, %15.12f, %15.12f' % (counter+1, x1, fxi\/dfxi, reldiff))\n\n # plot the tangents, points and intersections for finding the next xi\n # plot xi on the axis\n plt.plot(xi,0,'gx', markersize=16)\n # plot a line from xi on the axis up to the curve\n plt.vlines(xi, 0, fxi, colors='green', linestyles='dashed')\n \n # plot star on the curve where x=xi\n plt.plot(xi,fxi,'r*', markersize=16)\n # compute y values for tangent plotting\n tangy = dfxi*xvals + fxi - dfxi*xi\n # plot the tangent\n plt.plot(xvals, tangy, 'r--')\n # plot next xi on the axis\n plt.plot(x1,0,'gx', markersize=16)\n\n # trade output to input for next iteration step\n xi = x1\n # increase counter\n counter += 1\n\n # print test output\n print(chosenx0,x1,counter,reldiff)\n # remember counter for later plotting\n counter_chosen = counter\n\n plt.savefig('newton-method-example-plot-search.jpg', bbox_inches='tight')\n #plt.savefig('newton-method-example-plot-demo.jpg', bbox_inches='tight', dpi=300)\n \n # close figure 1\n plt.close()\n\n # begin plotting figure 2: overview of function and its derivative\n plt.figure()\n \n # plot the function f and its derivative\n #fx, dfx = f(xvals)\n fx, dfx = func(xvals)\n plt.plot(xvals, fx, label='$f(x)$')\n plt.plot(xvals, dfx, label=\"$f'(x)$\")\n \n # plot the zero line for easy reference\n plt.hlines(0, interval_left, interval_right)\n \n #label the axes\n plt.xlabel(\"$x$\", fontsize=16)\n# plt.ylabel(\"$y(x)$\", fontsize=16)\n \n # set limits for the x and y axes in the figure\n # set x limits\n plt.xlim((interval_left, interval_right))\n # we don't set y limits\n plt.ylim((interval_down, interval_up))\n \n # add legends to the plot\n plt.legend()\n \n # save the figure to an output file 1: overview of function and its derivative\n plt.savefig('newton-method-example-plot-overview.jpg', bbox_inches='tight')\n \n # carry on plotting figure 3: overview plus\n # loop over all starting points defined in pointlist\n for x0 in pointlist:\n # initialize values for iteration loop\n reldiff = 1\n xi = x0\n counter = 0\n # start iteration loop\n while reldiff > prec_goal and counter < nmax:\n \n # get the number of necessary iterations at that particular x0\n # compute relative difference\n fxi, dfxi = func(xi)\n reldiff = np.abs(fxi\/dfxi\/xi)\n # compute next xi\n x1 = xi - fxi\/dfxi\n# print('%i, %15.12f, %15.12f, %15.12f' % (counter+1, x1, fxi\/dfxi, reldiff))\n # trade output to input for next iteration step\n xi = x1\n # increase counter\n counter += 1\n \n # plot the number of necessary iterations at that particular x0\n plt.plot(x0,counter,'r.', markersize=5)\n# plt.plot(x0,counter,'r.', markersize=5, label=\"# of iterations\")\n # print test output\n# print(x0,x1,counter,reldiff)\n \n plt.plot(chosenx0,counter_chosen,'r.', markersize=5, label=\"# of iterations\")\n # add legends to the plot\n plt.legend()\n # save the figure to an output file\n plt.savefig('newton-method-example-plot-initial-guess-dependence.jpg', bbox_inches='tight')\n #plt.savefig('newton-method-example-plot-demo.jpg', bbox_inches='tight', dpi=300)\n \n plt.close()\n\n\n# call the solution function for func of your choice\nsolve_and_plot_newton(e9)\n<\/pre>\n\n\n\n