Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import numpy as np
- class NewtonLinearEquationSolver:
- EPS = 0.01
- MAX_ITER = 1000
- def __init__(self, linear_equations, jacobian):
- self.linear_equations = linear_equations
- self.jacobian = jacobian
- def solve(self, subtle_point):
- solution = subtle_point
- for i in range(NewtonLinearEquationSolver.MAX_ITER):
- linear_equation_at_point = [-f(*solution) for f in self.linear_equations]
- jacobian_at_point = [[f(*solution) for f in self.jacobian[idx]] for idx in range(len(self.jacobian))]
- new_solution = np.linalg.solve(np.matrix(jacobian_at_point), np.matrix(linear_equation_at_point).transpose())
- new_solution = [new_solution[idx].min() + solution[idx] for idx in range(len(new_solution))]
- if max([abs(new_solution[idx] - solution[idx]) for idx in range(len(new_solution))]) < NewtonLinearEquationSolver.EPS:
- print(f"Iterations: {i}")
- return new_solution
- solution = new_solution
- print(f"Iterations: {NewtonLinearEquationSolver.MAX_ITER}")
- return solution
- linear_equation = [lambda x, y: math.sin(x) + 2 * y - 2, lambda x, y: math.cos(y - 1) + x - 0.7]
- jacobian = [[lambda x, y: math.cos(x), lambda x, y: 2], [lambda x, y: 1, lambda x, y: -math.sin(y - 1)]]
- subtle_point = [0, 0]
- print(NewtonLinearEquationSolver(linear_equation, jacobian).solve(subtle_point))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement