Compare commits

..

16 Commits

Author SHA1 Message Date
fef143b824 bisekcja 2025-01-13 21:41:40 +01:00
2c23dba6e6 rungego-kutty dodane 2024-12-27 21:38:06 +01:00
9f3aed89f6 Dziwnie to nazwałem 2024-12-13 19:27:26 +01:00
d6e4e7dfb1 gaussa 2024-12-13 19:22:13 +01:00
33fb3e96b8 Merge branch 'main' of https://progit.zikor.pl/hamx/MO_pracadomowa 2024-12-05 22:26:41 +01:00
daf350c8ad Zmiana nazwy pliku 2024-12-05 22:26:34 +01:00
034d6883bf little fix 2024-12-03 23:01:46 +01:00
c1626d4008 rozniczkowanie zrobione 2024-12-03 23:00:11 +01:00
498867b9f2 do dokończenia 2024-12-03 13:46:30 +01:00
0f8b66f831 Generowanie x i y
Dodano na potrzeby punktu 7. w instrukcji
2024-12-02 22:26:57 +01:00
df9bc002e1 Działa aproksymacja 2024-12-02 21:51:59 +01:00
ce9b3f4a40 init aproksymacja 2024-11-16 22:24:43 +01:00
fc1666062c Delete editor.xml 2024-11-13 23:23:34 +01:00
ac7ca0beae little fix 2024-11-13 23:20:08 +01:00
98a3e97601 Done 2024-11-13 23:14:28 +01:00
889d6d0e7e temp result 2024-11-13 23:07:30 +01:00
10 changed files with 375 additions and 35 deletions

6
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"files.associations": {
"vector": "cpp",
"iostream": "cpp"
}
}

View File

@@ -4,4 +4,4 @@ project(MO_pracadomowa)
set(CMAKE_CXX_STANDARD 14)
add_executable(MO_pracadomowa
horner_simple.cpp)
main.cpp)

View File

@@ -0,0 +1,87 @@
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()

45
bisekcja/bisekcja.py Normal file
View File

@@ -0,0 +1,45 @@
from math import fabs
import matplotlib.pyplot as plt
import numpy as np
def f(x):
left_side = 2*np.cos(x + (np.pi/6)) + x**2
right_side = 4 * x - 3
return left_side - right_side
def oblicz(a,b):
x1,x2 = a,b
x = 0
epsi = 0.01
while(fabs(f(x)) > epsi):
x = (x1 + x2) / 2
y = f(x)
y1 = f(x1)
if y*y1 < 0:
x2 = x
elif y*y1 > 0:
x1 = x
return x
a,b = -2,7
print(f"Pierwiastek: {round(oblicz(a,b), 4)}")
x = np.linspace(-15, 15, 1000)
y = f(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y, label=r"$f(x) = 2\cos(x + \frac{\pi}{6}) + x^2 - (4x - 3)$", color="blue")
plt.axhline(0, color="black", linestyle="--", linewidth=0.8) # Add x-axis
plt.axvline(0, color="black", linestyle="--", linewidth=0.8) # Add y-
plt.axvline(a, color="red", linestyle="-", linewidth=2, label="a = {:.2f}".format(a))
plt.axvline(b, color="green", linestyle="-", linewidth=2, label="b = {:.2f}".format(b))
plt.title("Bisekcja")
plt.xlabel("x")
plt.ylabel("f(x)")
plt.legend()
plt.grid()
plt.show()

44
gaussa/gaussa.py Normal file
View File

@@ -0,0 +1,44 @@
def gaussa(a, b):
n = len(b)
for s in range(n - 1):
for i in range(s + 1, n):
factor = a[i][s] / a[s][s]
for j in range(s, n):
a[i][j] -= factor * a[s][j]
b[i] -= factor * b[s]
x = [0] * n
for i in range(n - 1, -1, -1):
x[i] = (b[i] - sum(a[i][j] * x[j] for j in range(i + 1, n))) / a[i][i]
return x
A = [
[4.88, -2.91, 1.34],
[1.34, 5.3, -3.31],
[2.18, -3.49, 6.7]
]
B = [7.86, -2.28, 4.47]
solutions = gaussa(A, B)
print("Macierz A:")
for x in A:
for a in x:
print(round(a, 2), end=" ")
print()
print()
print("Macierz B:")
for b in B:
print(round(b, 2), end=" ")
print("\n")
print("Wynik: ")
i = 1
for x in solutions:
print(f"x{i} = {round(x, 2)}")
i += 1

View File

@@ -1,3 +1,7 @@
#if WIN32
#include <algorithm>
#endif
#include <iostream>
#include <fstream>
#include <vector>

View File

@@ -3,6 +3,7 @@
#include <sstream>
#include <vector>
#include <iomanip>
#include <cmath>
using namespace std;
@@ -21,55 +22,106 @@ public:
while (getline(file, str))
{
istringstream iss(str);
if (iss >> a >> b) {
if (iss >> a >> b)
{
x.push_back(a);
y.push_back(b);
}
}
h = x[1] - x[0];
liczba_wezlow = x.size();
if (liczba_wezlow < 2)
{
cerr << "Za malo danych do interpolacji.\n";
exit(EXIT_FAILURE);
}
h = x[1] - x[0];
file.close();
}
void oblicz()
{
tablica_roznic.assign(liczba_wezlow, vector<float>(liczba_wezlow));
rowne_odstepy = true;
float pierwszy_odstep = x[1] - x[0];
for (int i = 0; i < liczba_wezlow; i++) {
tablica_roznic[i][0] = y[i];
}
for (int j = 1; j < liczba_wezlow; j++) {
for (int i = 0; i < liczba_wezlow - j; i++) {
tablica_roznic[i][j] = (tablica_roznic[i + 1][j - 1] - tablica_roznic[i][j - 1]);
// czy odstępy x są takie same?
for (int i = 2; i < liczba_wezlow; i++)
{
if (std::abs((x[i] - x[i - 1]) - pierwszy_odstep) > 1e-6)
{
rowne_odstepy = false;
break;
}
}
suma = tablica_roznic[0][0];
for (int i = 1; i < liczba_wezlow; i++) {
czynnik = tablica_roznic[0][i];
for (int j = 0; j < i; j++) {
czynnik *= (x[j] - x[0]);
if (rowne_odstepy)
{
// Newton
tablica_roznic.assign(liczba_wezlow, vector<float>(liczba_wezlow, 0));
for (int i = 0; i < liczba_wezlow; i++)
{
tablica_roznic[i][0] = y[i];
}
for (int j = 1; j < liczba_wezlow; j++)
{
for (int i = 0; i < liczba_wezlow - j; i++)
{
tablica_roznic[i][j] = (tablica_roznic[i + 1][j - 1] - tablica_roznic[i][j - 1]);
}
}
suma = tablica_roznic[0][0];
for (int i = 1; i < liczba_wezlow; i++)
{
czynnik = tablica_roznic[0][i];
for (int j = 0; j < i; j++)
{
czynnik *= (x[j] - x[0]);
}
suma += czynnik;
}
}
else
{
// Lagrange
suma = 0;
for (int i = 0; i < liczba_wezlow; i++)
{
float L = 1;
for (int j = 0; j < liczba_wezlow; j++)
{
if (i != j)
{
L *= (x[j] - x[0]) / (x[j] - x[i]);
}
}
suma += L * y[i];
}
suma += czynnik;
}
}
void wyswietl_tabela()
{
// nagłowki
cout << setw(5) << "i" << setw(10) << "x" << setw(10) << "y";
for (int j = 1; j < liczba_wezlow; ++j)
cout << setw(10) << "Δ^" + to_string(j);
cout << endl;
// wartości
for (int i = 0; i < liczba_wezlow; i++) {
cout << setw(5) << i << setw(10) << x[i];
for (int j = 0; j < liczba_wezlow - i; j++) {
cout << setw(10) << tablica_roznic[i][j];
}
if(rowne_odstepy) {
// nagłowki
cout << setw(5) << "i" << setw(10) << "x" << setw(10) << "y";
for (int j = 1; j < liczba_wezlow; ++j)
cout << setw(10) << "Δ^" + to_string(j);
cout << endl;
// wartości
for (int i = 0; i < liczba_wezlow; i++)
{
cout << setw(5) << i << setw(10) << x[i];
for (int j = 0; j < liczba_wezlow - i; j++)
{
cout << setw(10) << tablica_roznic[i][j];
}
cout << endl;
}
}
cout << "Interpolowany wynik: " << suma << endl;
@@ -78,6 +130,8 @@ public:
private:
float a, b, h, suma, czynnik;
int liczba_wezlow;
bool rowne_odstepy;
vector<float> x, y;
vector<vector<float> > tablica_roznic;
};

View File

@@ -1,6 +1,8 @@
1 2
1.5 2.5
2 3.5
2.5 4
3 5.3
3.5 6.0
0.09 1.23
0.15 1.34
0.20 1.39
0.27 1.46
0.35 1.54
0.40 1.59
0.46 1.66
0.50 1.80

View File

@@ -0,0 +1,65 @@
import math
from itertools import zip_longest
x = [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3]
y = [20, 22.222222, 8, 4.081633, 2.469136, 1.652893, 0.83665]
# # z instrukcji, tylko do testu
# x = [0.6, 0.7, 0.8, 0.9, 1.0]
# y = [-0.51083, -0.35667, -0.22314, -0.10536, 0.0]
h = math.ceil(x[1] - x[0])
def print_table(*columns):
def generate_headers(n):
headers = ["x", "f(x)"]
superscripts = ["\u2070", "\u00B9", "\u00B2", "\u00B3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"]
for i in range(1, n):
exp = ''.join(superscripts[int(digit)] for digit in str(i))
headers.append(f"{exp}f(x)")
return headers
headers = generate_headers(len(columns))
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)))
def oblicz(array):
result = []
current = array
for _ in range(len(array) - 1):
arr = [round(current[j] - current[j - 1], 5) for j in range(len(current) - 1, 0, -1)]
arr.reverse()
result.append(arr)
current = arr
return result
def wynik(array):
temp = []
suma = 0
for x in array:
temp.append(x[-1])
for x in temp:
if temp.index(x) == 0:
suma += x
elif temp.index(x) >= 1:
tik = 1/(temp.index(x) + 1)
suma += x*tik
print(f"f⁽¹⁾(x) = {round(suma*(1/h),5)}")
result = oblicz(y)
columns = [x, y] + result
print_table(*columns)
wynik(result)

View File

@@ -0,0 +1,33 @@
import numpy as np
x0 = 1.7
xk = 2.7
h = 0.1
y0 = 5.3
def f(x, y):
return x**2 + np.cos(y / np.pi)
def runge_kutta_4(f, x0, y0, h, xk):
n = int((xk - x0) / h) + 1
x = [x0 + i * h for i in range(n)]
y = [0] * n
y[0] = y0
print("Tabela wyników:")
print(f"{'i':<5}{'x':<10}{'y':<15}{'k1':<10}{'k2':<10}{'k3':<10}{'k4':<10}{'Δy':<10}")
for i in range(1, n):
k1 = h * f(x[i-1], y[i-1])
k2 = h * f(x[i-1] + h/2, y[i-1] + k1/2)
k3 = h * f(x[i-1] + h/2, y[i-1] + k2/2)
k4 = h * f(x[i-1] + h, y[i-1] + k3)
Δy = (k1 + 2*k2 + 2*k3 + k4) / 6
y[i] = y[i-1] + Δy
print(f"{i-1:<5}{x[i-1]:<10.2f}{y[i-1]:<15.5f}{k1:<10.5f}{k2:<10.5f}{k3:<10.5f}{k4:<10.5f}{Δy:<10.5f}")
print(f"{n-1:<5}{x[-1]:<10.2f}{y[-1]:<15.5f}")
return x, y
x, y = runge_kutta_4(f, x0, y0, h, xk)