Advertisement
EWTD

AdditionalLab1

Sep 22nd, 2023
1,281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. import math
  2. import numpy as np
  3.  
  4. class NewtonLinearEquationSolver:
  5.     EPS = 0.01
  6.     MAX_ITER = 1000
  7.  
  8.     def __init__(self, linear_equations, jacobian):
  9.         self.linear_equations = linear_equations
  10.         self.jacobian = jacobian
  11.  
  12.     def solve(self, subtle_point):
  13.         solution = subtle_point
  14.         for i in range(NewtonLinearEquationSolver.MAX_ITER):
  15.             linear_equation_at_point = [-f(*solution) for f in self.linear_equations]
  16.             jacobian_at_point = [[f(*solution) for f in self.jacobian[idx]] for idx in range(len(self.jacobian))]
  17.             new_solution = np.linalg.solve(np.matrix(jacobian_at_point), np.matrix(linear_equation_at_point).transpose())
  18.             new_solution = [new_solution[idx].min() + solution[idx] for idx in range(len(new_solution))]
  19.             if max([abs(new_solution[idx] - solution[idx]) for idx in range(len(new_solution))]) < NewtonLinearEquationSolver.EPS:
  20.                 print(f"Iterations: {i}")
  21.                 return new_solution
  22.             solution = new_solution
  23.         print(f"Iterations: {NewtonLinearEquationSolver.MAX_ITER}")
  24.         return solution
  25.  
  26.  
  27. linear_equation = [lambda x, y: math.sin(x) + 2 * y - 2, lambda x, y: math.cos(y - 1) + x - 0.7]
  28. jacobian = [[lambda x, y: math.cos(x), lambda x, y: 2], [lambda x, y: 1, lambda x, y: -math.sin(y - 1)]]
  29. subtle_point = [0, 0]
  30.  
  31. print(NewtonLinearEquationSolver(linear_equation, jacobian).solve(subtle_point))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement