Skip to content

Instantly share code, notes, and snippets.

@ramsays
Created March 7, 2019 03:39
Show Gist options
  • Save ramsays/769804e9e6fc204c81dee55537e297ca to your computer and use it in GitHub Desktop.
Save ramsays/769804e9e6fc204c81dee55537e297ca to your computer and use it in GitHub Desktop.
Newton-Raphson Algorithm
import numpy as np
def function(xy):
x, y = xy
return [2*x + y**2 - 8,
x**2 - y**2 + x*y - 3]
def jacobian(xy):
x, y = xy
return [[2, 2*x],
[2*x + y, x - 2*y]]
def iterative_newton(fun, x_init, jacobian, epsilon, max_iter):
x_last = x_init
for k in range(max_iter):
# Solve J(xn)*( xn+1 - xn ) = -F(xn):
J = np.array(jacobian(x_last))
F = np.array(fun(x_last))
diff = np.linalg.solve(J, -F)
x_last = x_last + diff
# Stop condition:
if np.linalg.norm(diff) < epsilon:
print('Convergence!, nre iter:', k )
break
else: # If loop ends without convergence
print('No convergence')
return x_last
xresult = iterative_newton(function, [0, 1], jacobian, 1e-4, 50)
print(xresult)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment