Namaru

Método de Jacobi

Sep 30th, 2025
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | Source Code | 0 0
  1. import numpy as np
  2.  
  3. def jacobi(A, b, tol=1e-10, max_iter=1000):
  4.     """
  5.    Resuelve sistemas de ecuaciones lineales Ax = b usando el metodo de Jacobi
  6.  
  7.    Parametros:
  8.        A: Matriz de coeficientes.
  9.        b: Vector de terminos independientes.
  10.        tol: Tolerancia para la convergencia.
  11.        max_iter: Maximo numero de iteraciones.
  12.  
  13.    Retorna:
  14.        x: Solucion aproximada.
  15.    """
  16.     n = len(b)
  17.     x = np.zeros(n)
  18.     x_new = np.zeros(n)
  19.  
  20.  
  21.     for k in range(max_iter):
  22.         for i in range(n):
  23.             x_new[i]= (b[i] - sum(A[i,j] * x[j] for j in range(n) if j != i))/A[i,i]
  24.  
  25.         if np.linalg.norm(x_new - x) < tol:
  26.             print(f"Total de iteraciones necesitadas: {k}")
  27.             return x_new
  28.        
  29.         x = x_new.copy()
  30.    
  31.     print(f"No se pudo converger en {max_iter} iteraciones.")
  32.     return x
  33.  
  34. A = np.array([[3,-0.1,-0.2],[0.1,7,-0.3],[0.3,-0.2,10]], dtype=float)
  35. b = np.array([7.85,-19.3,71.4], dtype=float)
  36.  
  37. ejemplo_jacobi =  jacobi(A,b)
  38. print(f"Solucion por gauss seidel: {ejemplo_jacobi}")
Advertisement
Add Comment
Please, Sign In to add comment