from itertools import zip_longest import matplotlib.pyplot as plt import numpy as np import random as rand def print_table(*columns, result): headers = ["Lp.", "x0", "x1", "x2", "x0y", "x1y"] max_widths = [ max(len(str(cell)) for cell in [header] + list(column)) for header, column in zip(headers, columns) ] def format_row(row): return " | ".join(f"{str(cell).ljust(width)}" for cell, width in zip(row, max_widths)) print(format_row(headers)) print("-" * (sum(max_widths) + 3 * (len(headers) - 1))) # Separator line for row in zip_longest(*columns, fillvalue=" "): print(format_row(row)) print("-" * (sum(max_widths) + 3 * (len(headers) - 1))) print(", ".join(result), end="\n\n") # 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, 6.32, 8.56] # y = [12.49, 4.76, 2.55, 1.60, 1.11, 0.82, 0.63, 0.50, 8.35, 5.23] # x = [1,2,3,4] # y = [6,5,7,10] x = [round(rand.uniform(-10, 10), 2) for _ in range(0,100)] y = [round(rand.uniform(1,2), 2) for _ in range(0, 100)] 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 print_table( [i for i in range(1, len(x)+1)], 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)}"] ) def a0(a1): return (t0 - s1 * a1) / s0 a1 = (t1 * s0 - s1 * t0) / (s2 * s0 - s1**2) a0 = a0(a1) # wynik print(f"a0 = {round(a0, 2)}, a1 = {round(a1, 2)}") # rysowanie funkcji i punktów 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) - 50, max(x) + 50) 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()