import numpy as np def cargar_temperaturas(nombre_archivo): temperaturas = {} archivo = open(nombre_archivo, "r") for linea in archivo: nombre, valor = linea.strip().split("=") temperaturas[nombre.strip()] = float(valor) archivo.close() return temperaturas def construir_sistema(TN, TS, TW, TE): A = np.array([ [4, -1, 0, -1, 0, 0], [-1, 4, -1, 0, -1, 0], [0, -1, 4, 0, 0, -1], [-1, 0, 0, 4, -1, 0], [0, -1, 0, -1, 4, -1], [0, 0, -1, 0, -1, 4] ], dtype=float) b = np.array([ TN + TW, TN, TN + TE, TW + TS, TS, TS + TE ], dtype=float) return A, b def pedir_factor_relajacion(): factor_relajacion = float( input("Ingrese el factor de relajacion (0 < w < 2): ") ) while factor_relajacion <= 0 or factor_relajacion >= 2: factor_relajacion = float( input( "Valor incorrecto. Ingrese un factor de relajacion entre 0 y 2: " ) ) return factor_relajacion def calcular_error(T, T_anterior): error = np.linalg.norm(T - T_anterior, 2) / np.linalg.norm(T, 2) return error def gauss_seidel_relajado(A, b, factor_relajacion, tolerancia, max_iteraciones): T = np.zeros(len(b)) archivo = open("temperaturas_iteraciones.txt", "w") archivo.write( "Iteracion\tT1\t\tT2\t\tT3\t\tT4\t\tT5\t\tT6\n" ) for iteracion in range(1, max_iteraciones + 1): T_anterior = T.copy() for i in range(len(T)): suma = 0 for j in range(len(T)): if j != i: suma += A[i, j] * T[j] T_GS = (b[i] - suma) / A[i, i] T[i] = (1 - factor_relajacion) * T_anterior[i] + \ factor_relajacion * T_GS error = calcular_error(T, T_anterior) archivo.write( f"{iteracion}\t" f"{T[0]:.8f}\t" f"{T[1]:.8f}\t" f"{T[2]:.8f}\t" f"{T[3]:.8f}\t" f"{T[4]:.8f}\t" f"{T[5]:.8f}\n" ) if error < tolerancia: archivo.close() return T, iteracion, error archivo.close() return T, max_iteraciones, error def mostrar_resultados(T, iteraciones, error): print("\nResultados:") print("-----------------------------") for i in range(len(T)): print(f"T{i + 1} = {T[i]:.8f} °C") print("-----------------------------") print(f"Iteraciones = {iteraciones}") print(f"Error final = {error:.10e}") # -------------------------------------------------- # Programa principal # -------------------------------------------------- temperaturas = cargar_temperaturas("temp.txt") TN = temperaturas["TN"] TS = temperaturas["TS"] TW = temperaturas["TW"] TE = temperaturas["TE"] A, b = construir_sistema( TN, TS, TW, TE ) factor_relajacion = pedir_factor_relajacion() tolerancia = 1e-6 max_iteraciones = 10000 T, iteraciones, error = gauss_seidel_relajado( A, b, factor_relajacion, tolerancia, max_iteraciones ) mostrar_resultados( T, iteraciones, error )