This repository has been archived on 2026-01-30. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
2025-10-08 21:36:44 +03:00

6.5 KiB

Solution of second-order linear ordinary differential equation

Input vars

In [ ]:
N = 20
linear_file = f"matrix_linear_{N}.txt"
cubic_file = f"matrix_cubic_{N}.txt"

System cells

In [ ]:
def write_to_file(name: str, array):
    with open(f"{name}", 'w') as file:
        for element in array:
            file.write(f"{element} ")
In [ ]:
import numpy as np
import matplotlib.pyplot as plt

Solution of 5u'' + 4u' + 1 = 0, u'(0) = u(0), u(10) = 5

In [ ]:
def u(x):
    return (9 * np.exp(8) * (x - 30) + 155 * np.exp(8 - 4 * x / 5) - 5 * (x + 1)) / (20 - 36 * np.exp(8))

Linear element

In [ ]:
def show_plot_linear(filename: str, elements: int):
    with open(filename, 'r') as file:
        data_str = file.read()

    x = np.linspace(0, 10, elements + 1)
    y = np.fromstring(data_str, sep=' ')
    y_real = u(x)

    plt.plot(x, y, label="Linear element solution", color='blue')
    plt.plot(x, y_real, label="Numeral solution", color='black')
    plt.title(f"Linear element, elements = {elements}")
    plt.grid(True)
    plt.xlabel("x")
    plt.ylabel("u(x)")
    plt.legend()
    plt.savefig(f"linear_{elements}.png", dpi=300)
    plt.show()

    write_to_file(f"linear_real_y_{elements}.txt", y_real)

Cubic element

In [ ]:
def show_plot_cubic(filename: str, elements: int):
    with open(filename, 'r') as file:
        data_str = file.read()

    x = np.linspace(0, 10, 3 * elements + 1)
    y = np.fromstring(data_str, sep=' ')
    y_real = u(x)

    plt.plot(x, y, label="Cubic element solution", color="red")
    plt.plot(x, y_real, label="Numeral solution", color='black')
    plt.title(f"Cubic element, elements = {elements} ")
    plt.xlabel("x")
    plt.ylabel("u(x)")
    plt.grid(True)
    plt.legend()
    plt.savefig(f"cubic_{elements}.png", dpi=300)
    plt.show()

    write_to_file(f"cubic_real_y_{elements}.txt", y_real)

Main part

In [ ]:
show_plot_linear(linear_file, N)
show_plot_cubic(cubic_file, N)

Errors

In [ ]:
def read_data_from_file(filename):
    with open(filename, 'r') as file:
        content = file.read().strip()
        data = np.array([float(x) for x in content.split()])
    return data
In [ ]:
def show_error(program_file: str, analytical_file: str):
    # Считывание данных из файлов
    real = read_data_from_file(analytical_file)
    matrix = read_data_from_file(program_file)
    
    absolute_errors = np.abs(real - matrix)
    relative_errors = absolute_errors / (np.abs(real))
    relative_errors_percent = relative_errors * 100

    max_relative_error = np.max(relative_errors)
    max_relative_error_percent = np.max(relative_errors_percent)
    max_error_index = np.argmax(relative_errors)

    print(f"\nМаксимальная относительная погрешность: {max_relative_error:.6f} ({max_relative_error_percent:.2f}%)")
    print(f"Индекс точки с максимальной погрешностью: {max_error_index}")
    print(f"Значения в точке с максимальной погрешностью:")
    print(f"  cubic_real: {real[max_error_index]}")
    print(f"  matrix_cubic: {matrix[max_error_index]}")
    print(f"  Абсолютная разность: {absolute_errors[max_error_index]:.6f}")
In [ ]:
show_error(linear_file, f"linear_real_y_{N}.txt")
show_error(cubic_file, f"cubic_real_y_{N}.txt")