Численные методы в Python: методы Гаусса-Зейделя, Якоби, Ньютона и методы деления пополам

Я могу предоставить вам программу на Python для метода Гаусса-Зейделя, а также других численных методов. Вот пример кода метода Гаусса-Зейделя:

def gauss_seidel(A, b, x0, tolerance, max_iterations):
    n = len(A)
    x = x0.copy()
    for k in range(max_iterations):
        for i in range(n):
            sum_ax = 0
            for j in range(n):
                if j != i:
                    sum_ax += A[i][j] * x[j]
            x[i] = (b[i] - sum_ax) / A[i][i]
        if all(abs(A.dot(x) - b) <= tolerance):
            return x
    return x
# Example usage
A = [[4, -1, 0], [1, 3, -1], [2, 0, 5]]
b = [1, 2, 3]
x0 = [0, 0, 0]
tolerance = 1e-6
max_iterations = 100
solution = gauss_seidel(A, b, x0, tolerance, max_iterations)
print("Solution:", solution)

Этот код определяет функцию gauss_seidel, которая принимает матрицу коэффициентов A, вектор констант b, начальное предположение x0, значение допуска для сходимости и максимальное разрешенное количество итераций. Он выполняет итерацию Гаусса-Зейделя до тех пор, пока решение не сойдётся или не будет достигнуто максимальное количество итераций.

Вот еще несколько числовых методов, которые могут оказаться вам полезными:

  1. Метод Якоби:

    def jacobi(A, b, x0, tolerance, max_iterations):
    n = len(A)
    x = x0.copy()
    for k in range(max_iterations):
        x_new = x.copy()
        for i in range(n):
            sum_ax = 0
            for j in range(n):
                if j != i:
                    sum_ax += A[i][j] * x[j]
            x_new[i] = (b[i] - sum_ax) / A[i][i]
    
        if all(abs(A.dot(x_new) - b) <= tolerance):
            return x_new
        x = x_new
    return x
    # Example usage
    A = [[4, -1, 0], [1, 3, -1], [2, 0, 5]]
    b = [1, 2, 3]
    x0 = [0, 0, 0]
    tolerance = 1e-6
    max_iterations = 100
    solution = jacobi(A, b, x0, tolerance, max_iterations)
    print("Solution:", solution)
  2. Метод Ньютона:

    def newton_method(f, f_prime, x0, tolerance, max_iterations):
    x = x0
    for k in range(max_iterations):
        fx = f(x)
        if abs(fx) <= tolerance:
            return x
    
        f_prime_x = f_prime(x)
        if f_prime_x == 0:
            break
    
        x = x - fx / f_prime_x
    return x
    # Example usage
    import math
    def f(x):
    return x2 - 2
    def f_prime(x):
    return 2 * x
    x0 = 1.5
    tolerance = 1e-6
    max_iterations = 100
    solution = newton_method(f, f_prime, x0, tolerance, max_iterations)
    print("Solution:", solution)
  3. Метод деления пополам:

    def bisection_method(f, a, b, tolerance, max_iterations):
    if f(a) * f(b) >= 0:
        raise ValueError("Function must have opposite signs at endpoints.")
    
    for k in range(max_iterations):
        c = (a + b) / 2
        if abs(f(c)) <= tolerance:
            return c
    
        if f(c) * f(a) < 0:
            b = c
        else:
            a = c
    return (a + b) / 2
    # Example usage
    import math
    def f(x):
    return x3 - x2 - x - 1
    a = 1
    b = 2
    tolerance = 1e-6
    max_iterations = 100
    solution = bisection_method(f, a, b, tolerance, max_iterations)
    print("Solution:", solution)