# -*- coding: utf-8 -*- # # newtonRaphson.py # # # Autor: Pedro Garcia Freitas # License: Creative Commons # # from math import fabs, exp def newtonRaphson(G, diffG, x0, errto, imax): """ return the root of a function (using the Newton-Raphson Method) newtonRaphson(fun, diffFun, x0, errto, imax) * fun: Function where find the roots * diffFun: analytic derivative of fun * x0: next point (estimative) * errto: tolerated error * imax: max of iterations allowed Author: Pedro Garcia see: http://www.sawp.com.br License: Creative Commons Dec 2009 """ x1 = x0 - G(x0)/diffG(x0) # fixed point x1 = G(x0) iterCount = 0 errno = fabs((x1 - x0)/x1) while errno > errto and iterCount < imax: x0 = x1 x1 = x0 - G(x0)/diffG(x0) # in fixed point will be x1 = G(x0) iterCount += 1 if x1 != 0: errno = fabs((x1 - x0)/x1) return x1 if __name__ == "__main__": f = lambda x: exp(-x) - x d2f = lambda x: -exp(-x) - 1 print newtonRaphson(f, d2f, 1.2, 0.0001, 100) f = lambda x: exp(-x) + x/5.0 - 1.0 df = lambda x: -exp(-x) + .20 print newtonRaphson(f, df, 1234e+10, 1e-14, 10000)