# -*- coding: utf-8 -*- # # secante.py # # # Autor: Pedro Garcia Freitas # License: Creative Commons # # from math import fabs, exp def secante(F, x0=1.0, xminus1=0.0, errto=0.001, imax=100): """ return the root of a function (using the Secant Method) secante(F, x0=1.0, xminus1=0.0, errto=0.001, imax=100) * F: Function where find the roots * x0: next point (estimative) * xminus: xi-1, used to define another bound * errto: tolerated error * imax: max of iterations allowed Author: Pedro Garcia see: http://www.sawp.com.br License: Creative Commons Dec 2009 """ iterCount = 0 errno = errto + 1 x1 = x0 x0 = xminus1 while errno > errto and iterCount < imax: xminus1 = x0 x0 = x1 # in Newton-Raphson will be x1 = x0 - G(x0)/diffG(x0) # in fixed point will be x1 = G(x0) x1 = x0 - (F(x0)*(xminus1 - x0))/(F(xminus1) - F(x0)) iterCount += 1 if x1 != 0: errno = fabs((x1 - x0)/x1) return x1 if __name__ == "__main__": print secante((lambda x: exp(-x) - x), 0, 1, 0.0001,100)