{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Newton method for square root" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Consider the function\n", "$$\n", "f(x) = x^2 - a\n", "$$\n", "The roots are $\\pm \\sqrt{a}$. The Newton method is\n", "$$\n", "x_{n+1} = \\frac{1}{2} \\left( x_n + \\frac{a}{x_n} \\right)\n", "$$" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "from math import sqrt\n", "a = 2.0\n", "r = sqrt(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Define the function and its derivative." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "def f(x):\n", " return x**2 - a\n", "\n", "def df(x):\n", " return 2.0*x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now implement Newton method as a function." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "def newton(f,df,x0,M=100,eps=1.0e-15):\n", " x = x0\n", " for i in range(M):\n", " dx = - f(x)/df(x)\n", " x = x + dx\n", " print('%3d %20.14f %20.14e %20.14e'%(i,x,x-r,abs(f(x))))\n", " if abs(dx) < eps * abs(x):\n", " return x\n", " print('No convergence, current root = %e' % x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We call Newton method with a complex initial guess for the root." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 0 1.50000000000000 8.57864376269049e-02 2.50000000000000e-01\n", " 1 1.41666666666667 2.45310429357160e-03 6.94444444444464e-03\n", " 2 1.41421568627451 2.12390141474117e-06 6.00730488287127e-06\n", " 3 1.41421356237469 1.59472435257157e-12 4.51061410444709e-12\n", " 4 1.41421356237310 0.00000000000000e+00 4.44089209850063e-16\n", " 5 1.41421356237309 -2.22044604925031e-16 4.44089209850063e-16\n" ] } ], "source": [ "x0 = 2.0\n", "x = newton(f,df,x0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "From the last column, we observe that in each iteration, the number of correct decimal places doubles." ] } ], "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.6" } }, "nbformat": 4, "nbformat_minor": 1 }