This repository has been archived on 2025-01-25. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
MO_pracadomowa/aproksymacja/main.py
2024-12-02 21:51:59 +01:00

88 lines
2.1 KiB
Python

from itertools import zip_longest
import matplotlib.pyplot as plt
import numpy as np
def print_table(*columns, result):
headers = ["x0", "x1", "x2", "x0y", "x1y"]
# 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)
]
# Function to format a row
def format_row(row):
return " | ".join(f"{str(cell).ljust(width)}" for cell, width in zip(row, max_widths))
# Print header
print(format_row(headers))
print("-" * (sum(max_widths) + 3 * (len(headers) - 1))) # Separator line
# Print rows
for row in zip_longest(*columns, fillvalue=" "):
print(format_row(row))
# Print result at the bottom
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]
# 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]
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(
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)}")
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()