1 #@ MODIF funct_root Utilitai DATE 14/09/2004 AUTEUR MCOURTOI M.COURTOIS
2 # -*- coding: iso-8859-1 -*-
3 ################################################################################
4 # Mathematical utility routines
5 # Copyright (C) 1999, Wesley Phoa
7 # Reference: Numerical Recipes in C
10 class BracketingException(Exception):
13 class RootFindingException(Exception):
16 class MinimizationException(Exception):
32 # UNIVARIATE ROOT FINDING
35 def bracket_root(f, interval, max_iterations=50):
37 Given a univariate function f and a tuple interval=(x1,x2),
38 return a new tuple (bracket, fnvals) where bracket=(x1,x2)
39 brackets a root of f and fnvals=(f(x1),f(x2)).
43 raise BracketingException("initial interval has zero width")
47 for j in range(max_iterations):
48 while f1*f2 >= 0: # not currently bracketed
50 x1 = x1 + GOLDEN*(x1-x2)
52 x2 = x2 + GOLDEN*(x2-x1)
54 return (x1, x2), (f1, f2)
55 raise BracketingException("too many iterations")
57 def ridder_root(f, bracket, fnvals=None, accuracy=1e-6, max_iterations=50):
59 Given a univariate function f and a tuple bracket=(x1,x2) bracketing a root,
60 find a root x of f using Ridder s method. Parameter fnvals=(f(x1),f(x2)) is optional.
72 raise BracketingException("initial interval does not bracket a root")
74 for j in range(max_iterations):
78 x4, x4old = x3 + (x3-x1)*sgn(f1-f2)*f3/temp**.5, x4
80 if f1*f4<0: # x1 and x4 bracket root
82 else: # x4 and x2 bracket root
84 if min(abs(x1-x2),abs(x4-x4old))<accuracy or temp==0:
86 raise RootFindingException("too many iterations")
88 def root(f, interval=(0.,1.), accuracy=1e-4, max_iterations=50):
90 Given a univariate function f and an optional interval (x1,x2),
91 find a root of f using bracket_root and ridder_root.
93 bracket, fnvals = bracket_root(f, interval, max_iterations)
94 return ridder_root(f, bracket, fnvals, accuracy, max_iterations)