diff --git a/aproksymacja/main.py b/aproksymacja/main.py index f934171..42e2f02 100644 --- a/aproksymacja/main.py +++ b/aproksymacja/main.py @@ -1,63 +1,87 @@ -from sympy import symbols, Eq, solve +from itertools import zip_longest +import matplotlib.pyplot as plt +import numpy as np -x = [1,2,4,5] -y = [3,4,6,7] -x0 = [1,1,1,1] -x1 = x[:] -x2 = [] -xy = [] +def print_table(*columns, result): + headers = ["x0", "x1", "x2", "x0y", "x1y"] -for number in x: - x2.append(number*number) + # Combine headers and columns to calculate max width for each column + max_widths = [ + max(len(str(cell)) for cell in [header] + list(column)) + for header, column in zip(headers, columns) + ] -x0y = y[:] + # Function to format a row + def format_row(row): + return " | ".join(f"{str(cell).ljust(width)}" for cell, width in zip(row, max_widths)) -for i in range(0,len(x)): - xy.append(x1[i] * x0y[i]) + # Print header + print(format_row(headers)) + print("-" * (sum(max_widths) + 3 * (len(headers) - 1))) # Separator line -s0 = 0 + # Print rows + for row in zip_longest(*columns, fillvalue=" "): + print(format_row(row)) -for x in x0: - s0=s0+x + # Print result at the bottom + print("-" * (sum(max_widths) + 3 * (len(headers) - 1))) + print(", ".join(result), end="\n\n") -s1 = 0 -for x in x1: - s1=s1+x +x = [1, 2, 4, 5] +y = [3, 4, 6, 7] +# x = [1.00, 1.71, 2.42, -3.13, 3.84, 4.55, 5.26, 5.97] +# y = [12.49, 4.76, 2.55, 1.60, 1.11, 0.82, 0.63, 0.50] +# x = [1,2,3,4] +# y = [6,5,7,10] -s2 = 0 +x0 = [1 for x in range(len(x))] # wszystkie 1 +s0 = sum(x0) # suma jedynek +s1 = sum(x) # suma x-sów +s2 = sum([a*a for a in x]) # suma x-sów do kwadratu +t0 = sum(y) # suma igreków +t1 = sum([a*b for a, b in zip(x, y)]) # suma x * y -for x in x2: - s2=s2+x +print_table( + x0, + x, + [round(a*a, 2) for a in x], + y, + [round(a*b, 2) for a, b in zip(x, y)], + result = [f"s0={round(s0, 2)}", f"s1={round(s1, 2)}", f"s2={round(s2, 2)}", f"t0={round(t0, 2)}", f"t1={round(t1, 2)}"] + ) -t0 = 0 -for x in x0y: - t0=t0+x +def a0(a1): + return (t0 - s1 * a1) / s0 -t1 = 0 -for x in xy: - t1=t1+x +a1 = (t1 * s0 - s1 * t0) / (s2 * s0 - s1**2) -print(f"{s0} {s1} {s2} {t0} {t1}") +a0 = a0(a1) -# Definiujemy zmienne -a0, a1 = symbols('a0 a1') -# Tworzymy równania -eq1 = Eq(4 * a0 + 12 * a1, 20) -eq2 = Eq(12 * a0 + 46 * a1, 70) - -# Rozwiązujemy układ równań -solution = solve((eq1, eq2), (a0, a1)) - -# Wyświetlamy wynik -print(solution) +# wynik +print(f"a0 = {round(a0, 2)}, a1 = {round(a1, 2)}") +plt.xlabel('oś x') +plt.ylabel('oś y') +plt.title('Aproksymacja - MNK') +plt.plot(x,y, 'o') +# plt.plot(x, [a0+a1*a for a in x]) # wzór z lekcji zastosowany +extended_x = np.linspace(min(x) - 2, max(x) + 5) +extended_y = a0 + a1 * extended_x + +plt.plot(extended_x, extended_y) + +plt.xlim(min(x)-1, max(x)+1) +plt.ylim(min(y)-2, max(y)+1) + +plt.show() +