Skip to content

Instantly share code, notes, and snippets.

@guanshaoheng
Created March 31, 2020 09:04
Show Gist options
  • Save guanshaoheng/264da402371c8018c794f07b77ca8397 to your computer and use it in GitHub Desktop.
Save guanshaoheng/264da402371c8018c794f07b77ca8397 to your computer and use it in GitHub Desktop.
Newton-Raphson method for nonlinear functions
"""
(修正)牛顿拉夫逊迭代 求解非线性方程组
"""
import numpy as np
import sympy as sp
class NewtonRaphsonSolver:
def __init__(self, p, x, f, tolerance=0.001):
self.p = p
self.x = x
self.f = f
self.k = p.jacobian(x)
self.tolerance = tolerance
self.k_inv = self.k.subs([(self.x[0], 1), (self.x[1], 2)]).inv()
self.ans = self.iterate(sp.Matrix([1, 0]))
def get_tangent(self, k, x):
return k.subs([(self.x[0], x[0]), (self.x[1], x[1])])
def iterate(self, x):
r = self.f-self.p.subs([(self.x[0], x[0]), (self.x[1], x[1])])
# Newton-Raphson iteration for nonlinear problem
# k = self.get_tangent(self.k, x)
# delta_x = k.inv()*r
# modified Newton-Raphson
delta_x = self.k_inv*r
if (delta_x.T*delta_x)[0] < self.tolerance*((x.T*x)[0]):
return delta_x+x
return self.iterate(x+delta_x)
x1, x2 = sp.symbols('x1 x2')
x = sp.Matrix([x1, x2])
a = sp.Matrix([[1, 1], [x1, x2]])
p = a*x
f = sp.Matrix([3, 9])
solution = NewtonRaphsonSolver(p, x, f)
print(solution.ans)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment