def broyden (func, x1, x2, tol = 1e-8): """ Implementation of the Broyden method finding roots to a multivariable func- tion. Inputs: func: The vector function you wish to find a root for x1: One initial guess vector x2: A second initial guess vector [tol]: optional. Tolerance level Returns: x such that func(x) = 0 """ if abs(func(x1)) < tol: return x1 if abs(func(x2)) < tol: return x2 x1Array = sp.array(x1) x2Array = sp.array(x2) jaco = Jacobian(func) f1 = func(x1) f2 = func(x2) deltax = (x2-x1) Jacob = jaco.jacobian(deltax) Jnew = Jacob + (f2- f1 - sp.dot(sp.dot(Jacob,deltax),deltax.T))\ /(la.norm(deltax)**2) xnew = la.inv(Jnew) * (-f2) + x2 x1 = x2 x2 = xnew Jacob = Jnew i=0 while abs(la.norm(func(xnew))) > tol: f1 = func(x1) f2 = func(x2) deltax = (x2-x1) Jnew = Jacob + (f2- f1 - sp.dot(sp.dot(Jacob,deltax),deltax.T))\ /(la.norm(deltax)**2) xnew = la.inv(Jnew) * (-f2) + x2 x1 = x2 x2 = xnew Jacob = Jnew i += 1 print i return xnew
def systemNewton(function, x0, fPrime = None, tol = 0.0001): epsilon = 1e-5 xArray = sp.array(x0, dtype = float) funArray = sp.array(function) numEqns = funArray.size numVars = xArray.size if numVars==1: if fPrime: return myNewNewton(function, x0, fPrime) else: return myNewNewton(function, x0) else: xold = xArray jacfun = Jacobian(function) jac0 = sp.mat(jacfun.jacobian(xold)) xnew = xold - la.solve(jac0,function(xold)) while max(abs(xnew-xold))> tol: xold = xnew jacNew = sp.mat(jacfun.jacobian(xold)) xnew = xold - la.solve(jacNew,function(xold)) return xnew