├── .gitignore
├── .idea
├── .gitignore
├── Numerical-Analysis-Code.iml
├── inspectionProfiles
│ └── profiles_settings.xml
├── misc.xml
├── modules.xml
└── vcs.xml
├── F(x)_Equation
├── chiadoi
│ ├── chiadoi.py
│ └── output_tn.txt
├── daycung
│ ├── daycung.py
│ ├── output_hn.txt
│ └── output_tn.txt
├── lapdon
│ ├── f(x)lapdon.py
│ ├── output_hn.txt
│ ├── output_tn.txt
│ └── test.py
└── tieptuyen
│ ├── output_hn.txt
│ ├── output_tn.txt
│ └── tieptuyen.py
├── Matrix_Equations
├── LapJacobi
│ ├── Jacobi.py
│ └── matrix.txt
├── gauss
│ ├── gauss_equations.py
│ └── matrix.txt
└── gauss_JD
│ ├── GJ_input.txt
│ ├── GJ_output.txt
│ └── gaussJD_equations.py
├── Min_max
└── min_max.py
├── README.md
└── dinhthuc
├── A.txt
└── gauss_method.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/.idea/Numerical-Analysis-Code.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/F(x)_Equation/chiadoi/chiadoi.py:
--------------------------------------------------------------------------------
1 | import math
2 | from numpy.lib import scimath
3 |
4 | num_decimal = 10 #Số chữ số thập phân hiển thị
5 |
6 | #Nhập phương trình cần giải
7 | def f(x):
8 | return 2*x**5 - 12*x**4 + 3*x**2 - 15
9 |
10 | def sign_f(x):
11 | if f(x) < 0:
12 | return -1
13 | elif f(x) > 0:
14 | return 1
15 | elif f(x) == 0:
16 | return 0
17 |
18 | def checkInput(a, b):
19 | if sign_f(a)*sign_f(b) > 0:
20 | print("Giá trị hàm tại hai đầu mút cùng dấu --> Kiểm tra lại đầu vào")
21 | return 0
22 | elif sign_f(a) == 0:
23 | print("Hàm số có nghiệm là đầu mút a = ", a)
24 | return 0
25 | elif sign_f(b) == 0:
26 | print("Hàm số có nghiệm là đầu mút b = ", b)
27 | return 0
28 | return 1
29 |
30 |
31 | def tien_nghiem(a, b):
32 | n = math.ceil(scimath.log2((b-a)/(eps)))
33 | print("Số lần lặp: ", n)
34 | #print("_"*110)
35 | #print("|{0:^9}|{1:^25}|{2:^30}|{3:^20}|{4:^20}|".format("Lần lặp", "Nghiệm x", "f(x)", "Đầu mút a", "Đầu mút b"))
36 | #print("-" * 110)
37 | fout.write("\n" + "_" * 110)
38 | fout.write("\n|{0:^9}|{1:^25}|{2:^30}|{3:^20}|{4:^20}|".format("Lần lặp", "Nghiệm x", "f(x)", "Đầu mút a", "Đầu mút b"))
39 | fout.write("\n" + "_" * 110)
40 | for i in range(n):
41 | x = (a + b) / 2
42 | if f(x) == 0:
43 | #print("|{0:^9}|{1:^25}|{2:^30}|{3:^20}|{4:^20}|".format(i + 1, round(x, num_decimal), round(f(x), num_decimal), round(a, num_decimal), round(b, num_decimal)))
44 | print("Phương trình đạt nghiệm đúng sau ", n, "lần lặp")
45 | fout.write("\n|{0:^9}|{1:^25}|{2:^30}|{3:^20}|{4:^20}|".format(i+1, round(x, num_decimal), round(f(x), num_decimal), round(a, num_decimal), round(b, num_decimal)))
46 | break
47 | elif f(a) * f(x) < 0:
48 | b = x
49 | #print("|{0:^9}|{1:^25}|{2:^30}|{3:^20}|{4:^20}|".format(i + 1, round(x, num_decimal), round(f(x), num_decimal), round(a, num_decimal), round(b, num_decimal)))
50 | fout.write("\n|{0:^9}|{1:^25}|{2:^30}|{3:^20}|{4:^20}|".format(i + 1, round(x, num_decimal), round(f(x), num_decimal), round(a, num_decimal), round(b, num_decimal)))
51 | elif f(x) * f(b) < 0:
52 | a = x
53 | #print("|{0:^9}|{1:^25}|{2:^30}|{3:^20}|{4:^20}|".format(i + 1, round(x, num_decimal), round(f(x), num_decimal), round(a, num_decimal), round(b, num_decimal)))
54 | fout.write("\n|{0:^9}|{1:^25}|{2:^30}|{3:^20}|{4:^20}|".format(i + 1, round(x, num_decimal), round(f(x), num_decimal), round(a, num_decimal), round(b, num_decimal)))
55 | fout.write("\n" + "_" * 110)
56 | return x
57 |
58 |
59 | if __name__ == "__main__":
60 | x0: float
61 | print("Nhập khoảng tìm nghiệm: ")
62 | a = float(input("Nhập a: "))
63 | b = float(input("Nhập b: "))
64 | eps = float(input("Nhập sai số: "))
65 | print()
66 | if checkInput(a, b) == 1:
67 | try:
68 | fout = open("output_tn.txt", mode='w', encoding='utf-8')
69 | if not (f(a) * f(b) > 0):
70 | x0 = tien_nghiem(a, b)
71 | print("Nghiệm gần đúng của phương trình là: ")
72 | print(x0)
73 | fout.write("\nNghiệm gần đúng của phương trình là: " + str(x0))
74 | else:
75 | print("Khoảng (", a, ",", b, ") không là khoảng phân ly nghiệm")
76 | finally:
77 | fout.close()
--------------------------------------------------------------------------------
/F(x)_Equation/chiadoi/output_tn.txt:
--------------------------------------------------------------------------------
1 |
2 | ______________________________________________________________________________________________________________
3 | | Lần lặp | Nghiệm x | f(x) | Đầu mút a | Đầu mút b |
4 | ______________________________________________________________________________________________________________
5 | | 1 | 0.0 | -15.0 | 0.0 | 10.0 |
6 | | 2 | 5.0 | -1190.0 | 5.0 | 10.0 |
7 | | 3 | 7.5 | 9645.9375 | 5.0 | 7.5 |
8 | | 4 | 6.25 | 865.126953125 | 5.0 | 6.25 |
9 | | 5 | 5.625 | -670.924987793 | 5.625 | 6.25 |
10 | | 6 | 5.9375 | -64.5930194855 | 5.9375 | 6.25 |
11 | | 7 | 6.09375 | 354.9485465884 | 5.9375 | 6.09375 |
12 | | 8 | 6.015625 | 134.486758234 | 5.9375 | 6.015625 |
13 | | 9 | 5.9765625 | 32.3515693404 | 5.9375 | 5.9765625 |
14 | | 10 | 5.95703125 | -16.760015233 | 5.95703125 | 5.9765625 |
15 | | 11 | 5.966796875 | 7.634769166 | 5.95703125 | 5.966796875 |
16 | | 12 | 5.9619140625 | -4.6027264311 | 5.9619140625 | 5.966796875 |
17 | | 13 | 5.9643554688 | 1.5059769716 | 5.9619140625 | 5.9643554688 |
18 | | 14 | 5.9631347656 | -1.5508835088 | 5.9631347656 | 5.9643554688 |
19 | | 15 | 5.9637451172 | -0.0230807533 | 5.9637451172 | 5.9643554688 |
20 | | 16 | 5.964050293 | 0.7412912018 | 5.9637451172 | 5.964050293 |
21 | | 17 | 5.9638977051 | 0.3590660019 | 5.9637451172 | 5.9638977051 |
22 | | 18 | 5.9638214111 | 0.1679828193 | 5.9637451172 | 5.9638214111 |
23 | | 19 | 5.9637832642 | 0.0724485819 | 5.9637451172 | 5.9637832642 |
24 | | 20 | 5.9637641907 | 0.0246833015 | 5.9637451172 | 5.9637641907 |
25 | | 21 | 5.9637546539 | 0.0008011209 | 5.9637451172 | 5.9637546539 |
26 | | 22 | 5.9637498856 | -0.0111398545 | 5.9637498856 | 5.9637546539 |
27 | | 23 | 5.9637522697 | -0.0051693763 | 5.9637522697 | 5.9637546539 |
28 | | 24 | 5.9637534618 | -0.0021841301 | 5.9637534618 | 5.9637546539 |
29 | | 25 | 5.9637540579 | -0.0006915052 | 5.9637540579 | 5.9637546539 |
30 | | 26 | 5.9637543559 | 5.48077e-05 | 5.9637540579 | 5.9637543559 |
31 | | 27 | 5.9637542069 | -0.0003183488 | 5.9637542069 | 5.9637543559 |
32 | | 28 | 5.9637542814 | -0.0001317705 | 5.9637542814 | 5.9637543559 |
33 | ______________________________________________________________________________________________________________
34 | Nghiệm gần đúng của phương trình là: 5.963754281401634
--------------------------------------------------------------------------------
/F(x)_Equation/daycung/daycung.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 |
4 | #Thay đổi khoảng vẽ đồ thị tại đây
5 | left = -5
6 | right = 5
7 |
8 | num_decimal = 15 # Số chữ số thập phân xuất hiện trong output
9 |
10 |
11 | delta = 1e-6
12 | MAXLOOP = 1e+6 # Số lần lặp tối đa cho đỡ vướng vào cái lặp vô hạn thôi
13 | eta = 1e-2
14 |
15 | #Phương trình f(x) = 0
16 | def f(x):
17 | return np.log(x)-1
18 |
19 |
20 | def df(x):
21 | return (f(x + delta) - f(x - delta)) / (2 * delta)
22 |
23 | def d2f(x):
24 | return (df(x + delta) - df(x - delta)) / (2 * delta)
25 |
26 | def dnf(x, deg):
27 | if deg == 1:
28 | return df(x)
29 | elif deg == 2:
30 | return d2f(x)
31 |
32 |
33 | def show_fx():
34 | plt.xlabel("y")
35 | plt.ylabel("x")
36 | plt.title("y = f(x) ")
37 | x = np.linspace(left, right, 1000)
38 | plt.plot(x, f(x))
39 | plt.plot(0, 0, '+')
40 | plt.plot(0, )
41 | plt.grid()
42 | plt.show()
43 |
44 | def menu():
45 | print("")
46 | print(" " * 20, "_" * 53)
47 | print(" " * 20, "|{0:51}|".format(" "))
48 | print(" " * 20, "|{0:^9}{1:^9}{0:^24}|".format(" ", "1. Sai số mục tiêu"))
49 | print(" " * 20, "|{0:^9}{1:^9}{0:^11}|".format(" ", "2. Sai số hai lần lặp liên tiếp"))
50 | print(" " * 20, "|{0:51}|".format(" "))
51 | print(" " * 20, "-" * 53)
52 | print("")
53 | print("")
54 |
55 | def gradient_descent(a, b, sign, deg): #sign = 1(cực tiểu)/-1(cực đại)
56 | x_ct = a
57 | count = 1
58 | while (not (abs(dnf(x_ct, deg)) < delta)):
59 | x_ct = x_ct - sign*eta * dnf(x_ct, deg)
60 | count += 1
61 | if count > MAXLOOP:
62 | break
63 | elif x_ct > b:
64 | #print("Hàm đơn điệu trên (", a, " , ", b, ")")
65 | break
66 | elif x_ct < a:
67 | break
68 | return x_ct
69 |
70 | def find_Extreme_of_theFuntion(left, right, deg):
71 | count = 2
72 | extreme = [left, right]
73 | while True:
74 | temp1 = gradient_descent(left, right, 1, deg)
75 | temp2 = gradient_descent(left, right, -1, deg)
76 | if (temp1 > right and temp2 < left) or (temp1 < left and temp2 > right):
77 | break
78 | if (temp1 > left) and (temp1 < right):
79 | extreme.append(temp1)
80 | left = extreme[count] + 0.05
81 | count += 1
82 |
83 | if (temp2 > left):
84 | if (temp2 < right):
85 | extreme.append(temp2)
86 | left = extreme[count] + 0.05
87 | count += 1
88 | if count > 2 and deg == 1:
89 | print("Hàm số tồn tại cực trị:",extreme[2:], "trên" , extreme[0], ",", extreme[1], "]")
90 | return extreme
91 |
92 |
93 |
94 | def check_input(left, right):
95 | if f(left) * f(right) > 0:
96 | return False
97 | if left > right:
98 | left, right = right, left
99 | ext = find_Extreme_of_theFuntion(left, right, 1)
100 | ext2 = find_Extreme_of_theFuntion(left, right, 2)
101 | if len(ext) == 2 and len(ext2) == 2:
102 | return True
103 | elif len(ext) > 2:
104 | print("f'(x) đổi dấu tại ít nhất 1 điểm: ", ext[2])
105 | return False
106 | elif len(ext2) > 2:
107 | print("f\"(x) đổi dấu tại ít nhất 1 điểm: ", ext2[2])
108 | return False
109 |
110 | def sai_so(x, x_old, M, m, ct_saisoi):
111 | if ct_saisoi == 1:
112 | return abs(f(x)) / m
113 | elif ct_saisoi == 2:
114 | return (M - m) * abs(x - x_old) / m
115 |
116 | def daycung(left, right, num):
117 | m = min(abs(df(a)), abs(df(b)))
118 | M = max(abs(df(a)), abs(df(b)))
119 | if f(left) * d2f(left) > 0: # Chọn right luôn là fourie
120 | left, right = right, left
121 | x = left # xấp xỉ nghiệm đầu = cực trái
122 | x_old = right
123 | Delta = sai_so(x, x_old, M, m, num)
124 | count = 0 # đếm số lần lặp
125 | fout.write("\n" + "_" * 85)
126 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|{3:^20}|".format("Lần lặp", "Nghiệm x", "f(x)", "Sai số"))
127 | fout.write("\n" + "_" * 85)
128 | while (not Delta < eps) and count < MAXLOOP:
129 | x_old = x
130 | x = x - f(x) * (right - x) / (f(right) - f(x))
131 | Delta = sai_so(x, x_old, M, m, num)
132 | count += 1
133 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|{3:^20}|".format(count, round(x, num_decimal), round(f(x), num_decimal), round(Delta, num_decimal)))
134 | fout.write("\n" + "_" * 85)
135 | return [x, count]
136 |
137 |
138 | if __name__ == "__main__":
139 | show_fx()
140 | print("Nhập khoảng tìm nghiệm: ")
141 | a = float(input("Nhập a: "))
142 | b = float(input("Nhập b: "))
143 | eps = float(input("Nhập sai số: "))
144 | print()
145 | check = check_input(a, b)
146 | if not check:
147 | print("Kiểm tra lại INPUT")
148 | else:
149 | menu()
150 | choose = int(input("Nhập lựa chọn: "))
151 | if choose == 1:
152 | fout = open("D:\\TLHT\\GTS-PPS\\codepython\\Tucode\GTS\\Numerical-Analysis-Code\\F(x)_Equation\\daycung\\output_tn.txt", mode='w', encoding='utf-8')
153 | x0 = daycung(a, b, 1)
154 | print("Nghiệm của phương trình: ", x0[0])
155 | print("Số lần lặp: ", x0[1])
156 | fout.write(f"\nNghiệm của phương trình: {x0[0]}")
157 | fout.close()
158 | elif choose == 2:
159 | fout = open("D:\\TLHT\\GTS-PPS\\codepython\\Tucode\GTS\\Numerical-Analysis-Code\\F(x)_Equation\\daycung\\output_hn.txt", mode='w', encoding='utf-8')
160 | x0 = daycung(a, b, 2)
161 | print("Nghiệm của phương trình: ", x0[0])
162 | print("Số lần lặp: ", x0[1])
163 | fout.write(f"\nNghiệm của phương trình: {x0[0]}")
164 | fout.close()
165 |
--------------------------------------------------------------------------------
/F(x)_Equation/daycung/output_hn.txt:
--------------------------------------------------------------------------------
1 |
2 | _____________________________________________________________________________________
3 | | Lần lặp | Nghiệm x | f(x) | Sai số |
4 | _____________________________________________________________________________________
5 | | 1 | 2.756792171024977 | 0.01406774690973 | 0.121603914447009 |
6 | | 2 | 2.723617728992986 | 0.001961044002238 | 0.016587221010471 |
7 | | 3 | 2.71902257840118 | 0.000272469551561 | 0.002297575295137 |
8 | | 4 | 2.718384689674588 | 3.7839810558e-05 | 0.00031894436319 |
9 | | 5 | 2.718296112392272 | 5.254751567e-06 | 4.4288641143e-05 |
10 | | 6 | 2.718283812023014 | 7.29712138e-07 | 6.150184627e-06 |
11 | | 7 | 2.718282103910406 | 1.01332887e-07 | 8.54056304e-07 |
12 | | 8 | 2.718281866710124 | 1.4071785e-08 | 1.18600141e-07 |
13 | | 9 | 2.718281833770854 | 1.954105e-09 | 1.6469635e-08 |
14 | _____________________________________________________________________________________
15 | Nghiệm của phương trình: 2.7182818337708543
--------------------------------------------------------------------------------
/F(x)_Equation/daycung/output_tn.txt:
--------------------------------------------------------------------------------
1 |
2 | _____________________________________________________________________________________
3 | | Lần lặp | Nghiệm x | f(x) | Sai số |
4 | _____________________________________________________________________________________
5 | | 1 | 2.7567922 | 0.0140677 | 0.0422032 |
6 | | 2 | 2.7236177 | 0.001961 | 0.0058831 |
7 | | 3 | 2.7190226 | 0.0002725 | 0.0008174 |
8 | | 4 | 2.7183847 | 3.78e-05 | 0.0001135 |
9 | | 5 | 2.7182961 | 5.3e-06 | 1.58e-05 |
10 | | 6 | 2.7182838 | 7e-07 | 2.2e-06 |
11 | | 7 | 2.7182821 | 1e-07 | 3e-07 |
12 | | 8 | 2.7182819 | 0.0 | 0.0 |
13 | | 9 | 2.7182818 | 0.0 | 0.0 |
14 | _____________________________________________________________________________________
15 | Nghiệm của phương trình: 2.7182818337708543
--------------------------------------------------------------------------------
/F(x)_Equation/lapdon/f(x)lapdon.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 | import math
4 |
5 | num_decimal = 7 # Số chữ số thập phân xuất hiện trong output
6 | delta = 1e-7
7 | MAXLOOP = 1e+7 # Số lần lặp tối đa
8 | eta = 1e-3
9 |
10 | def f(x): #Hàm f(x)
11 | return 0.01*x**3 - 2*x + 1
12 | def g(x): #Hàm g(x)/phi(x)
13 | return (0.01*x**3 + 1)/2
14 |
15 | def dg(x):
16 | return (g(x + delta) - g(x - delta)) / (2 * delta)
17 |
18 | def d2g(x):
19 | return (dg(x + delta) - dg(x - delta)) / (2 * delta)
20 |
21 | def show_fx():
22 | plt.xlabel("x")
23 | plt.ylabel("y")
24 | plt.title("Đồ thị biểu diễn phương trình x = g(x) ")
25 | x = np.linspace(b, a, 1000)
26 | plt.plot(x, g(x))
27 | plt.plot(x, x)
28 | plt.plot(0, 0, '+')
29 | plt.plot(0, )
30 | plt.grid()
31 | plt.show()
32 |
33 |
34 | def menu():
35 | print("")
36 | print(" " * 21, "_" * 45)
37 | print(" " * 20, "|{0:45}|".format(" "))
38 | print(" " * 20, "|{0:^9}{1:^9}{0:^15}|".format(" ", "1. Sai số tiên nghiệm"))
39 | print(" " * 20, "|{0:^9}{1:^9}{0:^16}|".format(" ", "2. Sai số hậu nghiệm"))
40 | print(" " * 20, "|{0:45}|".format(" "))
41 | print(" " * 21, "-" * 45)
42 | print("")
43 | print("")
44 |
45 |
46 | def gradient_descent(a, b, sign):
47 | x_ct = a
48 | x_new = x_ct - sign * eta * d2g(x_ct)
49 | count = 1
50 | while not (abs(d2g(x_ct)) < delta):
51 | x_ct = x_new
52 | x_new = x_ct - sign * eta * d2g(x_ct)
53 | count += 1
54 | if count > 1e+7:
55 | break
56 | if x_ct > b:
57 | # print("Hàm đơn điệu trên (", a, " , ", b, ")")
58 | return x_ct
59 | elif x_ct < a:
60 | # print("Hàm đang có xu hướng tăng -> tìm cực đại")
61 | return x_ct
62 | return x_ct
63 |
64 |
65 | def find_Extreme_of_theFuntion(left, right):
66 | count = 2
67 | extreme = [left, right]
68 | while True:
69 | temp1 = gradient_descent(left, right, 1)
70 | temp2 = gradient_descent(left, right, -1)
71 | if (temp1 > right and temp2 < left) or (temp1 < left and temp2 > right):
72 | break
73 | if (temp1 > left) and (temp1 < right):
74 | extreme.append(temp1)
75 | left = extreme[count] + 0.05
76 | count += 1
77 |
78 | if (temp2 > left):
79 | if (temp2 < right):
80 | extreme.append(temp2)
81 | left = extreme[count] + 0.05
82 | count += 1
83 | return extreme
84 |
85 |
86 | def check_input(left, right):
87 | global q
88 | if left > right:
89 | left = left + right
90 | right = left - right
91 | left = left - right
92 | ext = find_Extreme_of_theFuntion(left, right)
93 | dfext: list[float] = [] # Lưu giá trị đặc biệt của f'(x) để tìm MAX(f')
94 | for i in ext:
95 | dfext.append(abs(dg(i)))
96 | q = max(dfext)
97 | if q < 1:
98 | return True
99 | else:
100 | print("q = ", q, " >= 1")
101 | return False
102 |
103 |
104 | def lapdon(x0, q, num):
105 | x_old = x0 # xấp xỉ nghiệm đầu = cực trái
106 | x = g(x_old) # kiểm tra lần đầu để xác định sai số
107 |
108 | if num == 1:
109 | n = int(np.ceil(math.log((1 - q) * eps / abs(x - x_old), q)))
110 | fout.write("\n" + "_" * 65)
111 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|".format("Lần lặp", "Nghiệm x", "f(x)", "Sai số"))
112 | fout.write("\n" + "_" * 65)
113 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|".format(1, round(x, num_decimal), round(f(x), num_decimal)))
114 | for count in range(2, n + 1):
115 | x = g(x)
116 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|".format(count, round(x, num_decimal), round(f(x), num_decimal)))
117 | if f(x) == 0:
118 | print("\n Nghiệm đúng của phương trình f(x) = 0 là : ", x)
119 | break
120 | fout.write("\n" + "_" * 65)
121 |
122 | elif num == 2:
123 | Delta = q * abs(x - x_old) / (1 - q)
124 | count = 1
125 | fout.write("\n" + "_" * 85)
126 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|{3:^20}|".format("Lần lặp", "Nghiệm x", "f(x)", "Sai số"))
127 | fout.write("\n" + "_" * 85)
128 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|{3:^20}|".format(count, round(x, num_decimal), round(f(x), num_decimal),
129 | round(Delta, num_decimal)))
130 | while (not Delta < eps) and (count < MAXLOOP):
131 | x_old = x
132 | x = g(x)
133 | Delta = q * abs(x - x_old) / (1 - q)
134 | count += 1
135 | fout.write(
136 | "\n|{0:^10}|{1:^25}|{2:^25}|{3:^20}|".format(count, round(x, num_decimal), round(f(x), num_decimal),
137 | round(Delta, num_decimal)))
138 | fout.write("\n" + "_" * 85)
139 | return [x, count]
140 |
141 |
142 | if __name__ == "__main__":
143 | q = 1.0
144 | print("Nhập khoảng tìm nghiệm: ")
145 | a = float(input("Nhập a: "))
146 | b = float(input("Nhập b: "))
147 | eps = float(input("Nhập sai số: "))
148 | show_fx()
149 | check = check_input(a, b)
150 | if not check:
151 | print("Kiểm tra lại INPUT")
152 | elif check:
153 | menu()
154 | choose = int(input("Nhập lựa chọn: "))
155 | x0 = float(input("Xấp xỉ đầu: "))
156 | if choose == 1:
157 | fout = open("output_tn.txt", mode='w', encoding='utf-8')
158 | x = lapdon(x0, q, 1)
159 | if x[0] > a and x[0] < b:
160 | print("Nghiệm của phương trình: ", x[0])
161 | print("Số lần lặp: ", x[1])
162 | print("q = ", q)
163 | fout.write(f"\nNghiệm của phương trình: {x[0]}")
164 | else:
165 | print("Trong khoảng (", a, ",", b, ") không có nghiệm")
166 | fout.close()
167 | elif choose == 2:
168 | fout = open("output_hn.txt", mode='w', encoding='utf-8')
169 | x = lapdon(x0, q, 2)
170 | if x[0] > a and x[0] < b:
171 | print("Nghiệm của phương trình: ", x[0])
172 | print("Số lần lặp: ", x[1])
173 | print("q = ", q)
174 | fout.write(f"\nNghiệm của phương trình: {x[0]}")
175 | else:
176 | print("Trong khoảng (", a, ",", b, ") không có nghiệm")
177 | fout.close()
--------------------------------------------------------------------------------
/F(x)_Equation/lapdon/output_hn.txt:
--------------------------------------------------------------------------------
1 |
2 | _____________________________________________________________________________________
3 | | Lần lặp | Nghiệm x | f(x) | Sai số |
4 | _____________________________________________________________________________________
5 | | 1 | 0.50004 | 0.0011703 | 0.0191515 |
6 | | 2 | 0.5006252 | 4.4e-06 | 3.74e-05 |
7 | | 3 | 0.5006273 | 0.0 | 1e-07 |
8 | | 4 | 0.5006274 | 0.0 | 0.0 |
9 | _____________________________________________________________________________________
10 | Nghiệm của phương trình: 0.5006273555051369
--------------------------------------------------------------------------------
/F(x)_Equation/lapdon/output_tn.txt:
--------------------------------------------------------------------------------
1 |
2 | _________________________________________________________________
3 | | Lần lặp | Nghiệm x | f(x) |
4 | _________________________________________________________________
5 | | 1 | 0.54 | -0.0784254 |
6 | | 2 | 0.5007873 | -0.0003187 |
7 | | 3 | 0.500628 | -1.2e-06 |
8 | | 4 | 0.5006274 | -0.0 |
9 | | 5 | 0.5006274 | -0.0 |
10 | | 6 | 0.5006274 | -0.0 |
11 | | 7 | 0.5006274 | -0.0 |
12 | | 8 | 0.5006274 | 0.0 |
13 | _________________________________________________________________
--------------------------------------------------------------------------------
/F(x)_Equation/lapdon/test.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | for i in range(4, 6):
4 | print(i)
--------------------------------------------------------------------------------
/F(x)_Equation/tieptuyen/output_hn.txt:
--------------------------------------------------------------------------------
1 |
2 | _____________________________________________________________________________________
3 | | Lần lặp | Nghiệm x | f(x) | Sai số |
4 | _____________________________________________________________________________________
5 | | 1 | 2.6137056 | -0.039231 | 0.1426931 |
6 | | 2 | 2.7162439 | -0.00075 | 0.0039834 |
7 | | 3 | 2.7182811 | -3e-07 | 1.6e-06 |
8 | | 4 | 2.7182818 | -0.0 | 0.0 |
9 | _____________________________________________________________________________________
10 | Nghiệm của phương trình: 2.718281828458939
--------------------------------------------------------------------------------
/F(x)_Equation/tieptuyen/output_tn.txt:
--------------------------------------------------------------------------------
1 |
2 | _____________________________________________________________________________________
3 | | Lần lặp | Nghiệm x | f(x) | Sai số |
4 | _____________________________________________________________________________________
5 | | 1 | 2.6137056 | -0.039231 | 0.117693 |
6 | | 2 | 2.7162439 | -0.00075 | 0.00225 |
7 | | 3 | 2.7182811 | -3e-07 | 8e-07 |
8 | | 4 | 2.7182818 | -0.0 | 0.0 |
9 | _____________________________________________________________________________________
10 | Nghiệm của phương trình: 2.718281828458939
--------------------------------------------------------------------------------
/F(x)_Equation/tieptuyen/tieptuyen.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import math
3 | import matplotlib.pyplot as plt
4 |
5 | #Thay đổi khoảng vẽ đồ thị tại đây
6 | left = 0
7 | right = 10
8 |
9 | num_decimal = 7 # Số chữ số thập phân xuất hiện trong output
10 |
11 | delta = 1e-7 #dùng để xấp xỉ đạo hàm hai phía
12 | MAXLOOP = 1e+7 # Số lần lặp tối đa
13 | eta = 1e-3
14 |
15 |
16 | def f(x):
17 | return np.log(x) - 1
18 |
19 |
20 | def df(x):
21 | return (f(x + delta) - f(x - delta)) / (2 * delta)
22 |
23 |
24 | def d2f(x):
25 | return (df(x + delta) - df(x - delta)) / (2 * delta)
26 |
27 |
28 | def dnf(x, deg):
29 | if deg == 1:
30 | return df(x)
31 | elif deg == 2:
32 | return d2f(x)
33 | elif deg == 3:
34 | return (d2f(x + delta) - d2f(x - delta)) / (2 * delta)
35 |
36 |
37 | def show_fx():
38 | plt.xlabel("x")
39 | plt.ylabel("y")
40 | plt.title("Đồ thị hàm số của phương trình f(x) ")
41 | x = np.linspace(left, right, 100)
42 | plt.plot(x, f(x))
43 | plt.plot(0, 0, '+')
44 | plt.plot(0, )
45 | plt.grid()
46 | plt.show()
47 |
48 |
49 | def menu():
50 | print("")
51 | print(" " * 20, "_" * 53)
52 | print(" " * 20, "|{0:51}|".format(" "))
53 | print(" " * 20, "|{0:^9}{1:^9}{0:^24}|".format(" ", "1. Sai số mục tiêu"))
54 | print(" " * 20, "|{0:^9}{1:^9}{0:^11}|".format(" ", "2. Sai số hai lần lặp liên tiếp"))
55 | print(" " * 20, "|{0:51}|".format(" "))
56 | print(" " * 20, "-" * 53)
57 | print("")
58 | print("")
59 |
60 |
61 | def gradient_descent(a, b, sign, deg): #sign = 1(cực tiểu)/-1(cực đại)
62 | x_ct = a
63 | count = 1
64 | while (not (abs(dnf(x_ct, deg)) < delta)):
65 | x_ct = x_ct - sign*eta * dnf(x_ct, deg)
66 | count += 1
67 | if count > MAXLOOP:
68 | break
69 | elif x_ct > b:
70 | #print("Hàm đơn điệu trên (", a, " , ", b, ")")
71 | break
72 | elif x_ct < a:
73 | break
74 | return x_ct
75 |
76 |
77 | def find_Extreme_of_theFuntion(left, right, deg):
78 | count = 2
79 | extreme = [left, right]
80 | while True:
81 | temp1 = gradient_descent(left, right, 1, deg)
82 | temp2 = gradient_descent(left, right, -1, deg)
83 | if (temp1 > right and temp2 < left) or (temp1 < left and temp2 > right):
84 | break
85 | if (temp1 > left) and (temp1 < right):
86 | extreme.append(temp1)
87 | left = extreme[count] + 0.1
88 | count += 1
89 |
90 | if (temp2 > left):
91 | if (temp2 < right):
92 | extreme.append(temp2)
93 | left = extreme[count] + 0.1
94 | count += 1
95 | if count > 2 and deg == 1:
96 | print("Hàm số tồn tại cực trị:", extreme[2:], "trên", extreme[0], ",", extreme[1], "]")
97 | return extreme
98 |
99 |
100 | def check_input(left, right):
101 | if f(left) * f(right) > 0:
102 | return False
103 | if left > right:
104 | left, right = right, left
105 | ext = find_Extreme_of_theFuntion(left, right, 1)
106 | ext2 = find_Extreme_of_theFuntion(left, right, 2)
107 | if len(ext) == 2 and len(ext2) == 2:
108 | return True
109 | elif len(ext) > 2:
110 | print("f'(x) đổi dấu tại ít nhất 1 điểm: ", ext[2])
111 | return False
112 | elif len(ext2) > 2:
113 | print("f\"(x) đổi dấu tại ít nhất 1 điểm: ", ext2[2])
114 | return False
115 |
116 |
117 | def sai_so(x, x_old, M, m, ct_saisoi):
118 | if ct_saisoi == 1:
119 | return abs(f(x)) / m
120 | elif ct_saisoi == 2:
121 | return (M * (x - x_old) ** 2) / (2 * m)
122 |
123 |
124 | def tieptuyen(left, right, num):
125 | valExt = []
126 | extreme = find_Extreme_of_theFuntion(left, right, 3)
127 | for i in extreme:
128 | valExt.append(abs(d2f(i)))
129 | m = min(abs(df(left)), abs(df(right)))
130 | M = max(valExt)
131 | if f(left) * d2f(left) > 0: # Chọn right luôn là fourie
132 | left, right = right, left
133 | x_old = right # xấp xỉ nghiệm đầu = cực phải
134 | x = x_old - f(x_old) / df(x_old)
135 | Delta = sai_so(x, x_old, M, m, num)
136 | count = 1 # đếm số lần lặp
137 | fout.write("\n" + "_" * 85)
138 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|{3:^20}|".format("Lần lặp", "Nghiệm x", "f(x)", "Sai số"))
139 | fout.write("\n" + "_" * 85)
140 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|{3:^20}|".format(count, round(x, num_decimal), round(f(x), num_decimal),
141 | round(Delta, num_decimal)))
142 | while (not Delta < eps) and (count < MAXLOOP):
143 | x_old = x
144 | x = x_old - f(x_old) / df(x_old)
145 | Delta = sai_so(x, x_old, M, m, num)
146 | count += 1
147 | fout.write("\n|{0:^10}|{1:^25}|{2:^25}|{3:^20}|".format(count, round(x, num_decimal), round(f(x), num_decimal),
148 | round(Delta, num_decimal)))
149 | fout.write("\n" + "_" * 85)
150 | return [x, count]
151 |
152 |
153 | if __name__ == "__main__":
154 | show_fx()
155 | print("Nhập khoảng tìm nghiệm: ")
156 | a = float(input("Nhập a: "))
157 | b = float(input("Nhập b: "))
158 | eps = float(input("Nhập sai số: "))
159 | print()
160 | # show_fx(a, b)
161 | check = check_input(a, b)
162 | if not check:
163 | print("Kiểm tra lại INPUT")
164 | elif check:
165 | menu()
166 | choose = int(input("Nhập lựa chọn: "))
167 | if choose == 1:
168 | fout = open("D:\\TLHT\\GTS-PPS\\codepython\\Tucode\GTS\\Numerical-Analysis-Code\\F(x)_Equation\\tieptuyen\\output_tn.txt", mode='w', encoding='utf-8')
169 | x0 = tieptuyen(a, b, 1)
170 | print("Nghiệm của phương trình: ", x0[0])
171 | print("Số lần lặp: ", x0[1])
172 | fout.write(f"\nNghiệm của phương trình: {x0[0]}")
173 | fout.close()
174 | elif choose == 2:
175 | fout = open("D:\\TLHT\\GTS-PPS\\codepython\\Tucode\GTS\\Numerical-Analysis-Code\\F(x)_Equation\\tieptuyen\\output_hn.txt", mode='w', encoding='utf-8')
176 | x0 = tieptuyen(a, b, 2)
177 | print("Nghiệm của phương trình: ", x0[0])
178 | print("Số lần lặp: ", x0[1])
179 | fout.write(f"\nNghiệm của phương trình: {x0[0]}")
180 | fout.close()
181 |
--------------------------------------------------------------------------------
/Matrix_Equations/LapJacobi/Jacobi.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | def Cheotroihang(A, b):
4 | for i in range(A.shape[0]):
5 | max = abs(A[i, i])
6 | for j in range(A.shape[0]):
7 | if i == j:
8 | continue
9 | max -= abs(A[i, j])
10 | if max <= 0:
11 | return False
12 |
13 | return True
14 |
15 | def Cheotroicot(A, b):
16 | for i in range(A.shape[0]):
17 | max = abs(A[i, i])
18 | for j in range(A.shape[0]):
19 | if i == j:
20 | continue
21 | max -= abs(A[j, i])
22 | if max <= 0:
23 | return False
24 |
25 | return True
26 |
27 |
28 |
29 | def Jacobi_method(A, b, eps):
30 |
31 | if Cheotroihang(A, b):
32 | print("Ma trận thỏa mãn chéo trội hàng")
33 | for i in range(A.shape[0]):
34 | b[i] = b[i]/A[i, i]
35 | A[i, :] = A[i,:]/A[i, i]
36 |
37 | alpha = np.eye(A.shape[0]) - A
38 | q = np.linalg.norm(alpha.T, 1)
39 | print("q = ", q)
40 | print("alpha = " ,alpha)
41 | print("beta = ", b)
42 | print("\n\n")
43 | x0 = np.zeros(len(b))
44 | x = x0
45 | k = 0
46 | while(True):
47 | x = alpha@x.T + b
48 | print("Lần lặp thứ {0}: \n {1}".format(k+1, x))
49 | saiso = q*np.linalg.norm(x-x0, ord=1)/(1-q)
50 | if saiso < eps:
51 | print("Sai số: ", saiso)
52 | return x
53 | x0 = x
54 | k = k+1
55 | elif Cheotroicot(A, b):
56 | print("Ma trận thỏa mãn chéo trội cột")
57 | T = np.zeros(A.shape)
58 | max_a = abs(A[0, 0])
59 | min_a = abs(A[0, 0])
60 | for i in range(A.shape[0]):
61 | T[i, i] = 1/A[i, i]
62 | if max_a < abs(A[i, i]):
63 | max_a = abs(A[i, i])
64 | if min_a > abs(A[i, i]):
65 | min_a = abs(A[i, i])
66 | Lambda = max_a/min_a
67 | alpha = np.eye(A.shape[0]) - T@A
68 | beta = T@b
69 | q = np.linalg.norm(alpha, 1)
70 | print("q = ", q)
71 | print("alpha = " ,alpha)
72 | print("beta = ", beta)
73 | print("\n\n")
74 | x0 = np.ones(len(b))
75 | x = x0
76 | k= 0
77 | while(True):
78 | x = alpha@x.T + beta
79 | print("Lần lặp thứ {0}: \n {1}".format(k+1, x))
80 | saiso = Lambda*q*np.linalg.norm(x-x0, ord=1)/(1-q)
81 | if saiso < eps:
82 | print("Sai số: ", saiso)
83 | return x
84 | print(x)
85 | x0 = x
86 | k = k + 1
87 |
88 | else:
89 | print("Ma trận không thỏa mãn chéo trội")
90 |
91 |
92 |
93 | if __name__ == "__main__":
94 | #input matrix [A|b]
95 | path = "D:\\TLHT\\GTS-PPS\\codepython\\Tucode\\GTS\\Numerical-Analysis-Code\\Matrix_Equations\\LapJacobi\\matrix.txt"
96 | with open(path, "r") as file:
97 | # Read the matrix from the file, assuming that the values are space-separated
98 | matrix = np.loadtxt(file)
99 |
100 | A = matrix[:, :-1]
101 | A_b = np.array(matrix)
102 | b = matrix[:, -1]
103 | eps = 1e-10 #Sai số
104 | sochuso = 10 #Số chữ số sau dấu phẩy
105 | Sol = Jacobi_method(A, b, eps)
106 | print("Nghiệm gần đúng: ", Sol)
107 | print("Kiểm tra kết quả: Ax = ", A_b[:, :-1]@Sol)
108 |
109 |
--------------------------------------------------------------------------------
/Matrix_Equations/LapJacobi/matrix.txt:
--------------------------------------------------------------------------------
1 | 5.1 1.1 1.2 1.0 6.3
2 | 1.1 6.1 1.0 1.1 2.1
3 | 1.2 1.0 7.1 1.0 8.3
4 | 1.0 1.1 1.0 5.1 2.0
--------------------------------------------------------------------------------
/Matrix_Equations/gauss/gauss_equations.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 |
4 | def gauss_elimination(A: np.matrix):
5 | n = A.shape[0]
6 | p = -1
7 | for i in range(0, n - 1):
8 | for p in range(i, n + 1):
9 | if p == n:
10 | print("no unique solution exists")
11 | return
12 | if A[p, i] != 0:
13 | break
14 | if p != i:
15 | A[[p, i]] = A[[i, p]]
16 | for j in range(i + 1, n):
17 | A[j] = A[j] - (A[j, i] / A[i, i]) * A[i]
18 | print("Bước thứ ", i+1)
19 | print(A)
20 | print("Kết thúc quá trình đưa ma trận về dạng bậc thang: ")
21 | print("Ma trận [A|b] sau biến đổi: \n", A)
22 | if A[n - 1, n - 1] == 0:
23 | print("no unique solution exists")
24 | return
25 | x = np.zeros(n)
26 | x[n - 1] = A[n - 1, n] / A[n - 1, n - 1]
27 | for i in range(n - 1, -1, -1):
28 | sig = 0
29 | for j in range(i + 1, n):
30 | sig += A[i, j] * x[j]
31 | x[i] = (A[i, n] - sig) / A[i, i]
32 | return x
33 |
34 |
35 | if __name__ == "__main__":
36 | #input matrix [A|b]
37 | path = "D:\\TLHT\\GTS-PPS\\codepython\\Tucode\\GTS\\Numerical-Analysis-Code\\Matrix_Equations\\gauss\\matrix.txt"
38 | with open(path, "r") as file:
39 | # Read the matrix from the file, assuming that the values are space-separated
40 | A = np.loadtxt(file)
41 | print("Ma trận [A|b] ban đầu: \n", A)
42 | x = gauss_elimination(A)
43 | print("---------------------------")
44 | print("Nghiệm của hệ: x = ", x)
45 | print("---------------------------")
46 | print("Kiểm tra nghiệm A*x = ", A[:, :-1]@x.T)
47 |
48 |
49 |
--------------------------------------------------------------------------------
/Matrix_Equations/gauss/matrix.txt:
--------------------------------------------------------------------------------
1 | 0.0000000001 1000 400 3
2 | 3000 0.03 50 4
3 | 99 1 0 666
--------------------------------------------------------------------------------
/Matrix_Equations/gauss_JD/GJ_input.txt:
--------------------------------------------------------------------------------
1 | 0.0000000001 1000 400 3
2 | 3000 0.03 50 4
3 | 99 1 0 666
--------------------------------------------------------------------------------
/Matrix_Equations/gauss_JD/GJ_output.txt:
--------------------------------------------------------------------------------
1 | 5.41462 0.00000 0.00000 0.00000
2 | 129.95298 0.00000 0.00000 0.00000
3 | -324.87495 0.00000 0.00000 0.00000
4 |
--------------------------------------------------------------------------------
/Matrix_Equations/gauss_JD/gaussJD_equations.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 |
3 | path = 'D:\\TLHT\\GTS-PPS\\codepython\\Tucode\\GTS\\Numerical-Analysis-Code\\Matrix_Equations\\gauss_JD\\'
4 |
5 |
6 | class Gauss_Jordan_Algorithms:
7 | np.set_printoptions(suppress=True, linewidth=np.inf, precision=10)
8 |
9 |
10 | matrix = np.genfromtxt(path + 'GJ_input.txt', delimiter=' ')
11 | A = matrix[:, :-1] #Lưu lại ma trận ban đầu để lát kiểm tra tính đúng của nghiệm
12 | index_row = [] # Khởi tạo mảng lưu các hàng của phần tử giải (theo thứ tự)
13 | index_column = [] # Khởi tạo mảng lưu các cột của phần tử giải (theo thứ tự)
14 | result = np.zeros(
15 | (len(matrix[0]) - 1, len(matrix[0]))) # Khởi tạo ma trận lưu kết quả với các giá trị ban đầu bằng 0
16 |
17 | def solutions_checker(self):
18 | """Trong trường hợp nghiệm duy nhất, hàm được sử dụng để kiểm tra lại nghiệm
19 | bằng cách nhân lại ma trận kết quả với hệ số ban đầu"""
20 | A = np.loadtxt("input.txt", delimiter=' ')[:, :-1] # ma trận hệ số trong phương trình AX=B
21 | print()
22 | print("- - - - - Kiểm tra nghiệm - - - - -")
23 | print(np.matmul(A, np.delete(self.result, np.s_[1:], axis=1))) # In ra ma trận A * ma trận X
24 |
25 | def find_pivot_element(self):
26 | """Hàm được dùng để tìm phần tử giải"""
27 | # global index_row, index_column
28 | index_temp = []
29 | pivot_element = 0
30 | for row in range(0, len(self.matrix)):
31 | if row in self.index_row:
32 | continue # Bỏ qua vì hàng này đã có phần tử giải
33 | max_row = np.amax(abs(self.matrix[row, 0:(len(self.matrix[0]) - 1)])) # Tìm phần tử lớn nhất trong hàng row
34 | if (1 in self.matrix[row, 0:(len(self.matrix[0]) - 1)]) or (
35 | -1 in self.matrix[row,
36 | 0:(len(self.matrix[0]) - 1)]): # Nếu có 1 hoặc -1 trong hàng row => chọn làm phần tử giải
37 | pivot_element = 1
38 | row_pivot_element = row
39 | index_temp = np.where(abs(self.matrix[row, 0:(len(self.matrix[0]) - 1)]) == pivot_element)
40 | index_temp = index_temp[:1]
41 | index_temp = index_temp[0][0]
42 | break
43 | elif max_row > pivot_element: # Lưu giá trị phần tử giải, tìm vị trí trên ma trận
44 | pivot_element = max_row
45 | row_pivot_element = row
46 | index_temp = np.where(abs(self.matrix[row, 0:(len(self.matrix[0]) - 1)]) == pivot_element)
47 | index_temp = index_temp[:1]
48 | index_temp = index_temp[0][0]
49 | if pivot_element != 0: # Lưu vị trí hàng và cột của phần tử giải
50 | self.index_row.append(row_pivot_element)
51 | self.index_column.append(int(index_temp))
52 | """ In ra giá trị và vị trí phần tử giải"""
53 | print()
54 | print("Phần tử giải: ", round(self.matrix[self.index_row[-1]][self.index_column[-1]], 10))
55 | print("Vị trí: ", self.index_row[-1] + 1, self.index_column[-1] + 1)
56 | print()
57 |
58 | def Gauss_Jordan_method(self):
59 | """Phương pháp Gauss - Jordan"""
60 | global matrix
61 | self.find_pivot_element()
62 | zeros_array = np.zeros((len(self.matrix), len(self.matrix[0]))) # Tạo 1 ma trận không
63 | for row in range(0, len(self.matrix)):
64 | if row == self.index_row[-1]:
65 | continue
66 | m = - self.matrix[row][self.index_column[-1]] / self.matrix[self.index_row[-1]][
67 | self.index_column[-1]] # Tìm m
68 | zeros_array[row] = self.matrix[self.index_row[-1]] * m
69 | self.matrix = self.matrix + zeros_array
70 |
71 | def normalize_pivot_element(self):
72 | """Chuẩn hóa hệ số của phần tử giải (chia để hệ số của phần tử giải =1)"""
73 | for i in range(len(self.index_row)):
74 | self.matrix[self.index_row[i]] = self.matrix[self.index_row[i]] / self.matrix[self.index_row[i]][
75 | self.index_column[i]]
76 | print("Ma trận sau khi chuẩn hóa hệ số: ")
77 | print(self.matrix)
78 |
79 | def rank(self):
80 | """Tìm hạng của ma trận hệ số A và hạng của ma trận mở rộng"""
81 | rank1 = 0 # Hạng của ma trận hệ số A
82 | rank2 = 0 # Hạng của ma trận mở rộng
83 | for row in range(0, len(self.matrix)):
84 | if np.amax(abs(self.matrix[row, 0:(len(self.matrix[0]) - 1)])) > 0:
85 | rank1 = rank1 + 1
86 | if np.amax(abs(self.matrix[row, 0:len(self.matrix[0])])) > 0:
87 | rank2 = rank2 + 1
88 | if rank1 < rank2:
89 | print("Hệ PT vô nghiệm...Niệm!")
90 | f=open(path + 'GJ_output.txt',"w")
91 | f.write("Hệ PT vô nghiệm...Niệm!")
92 | f.close()
93 | elif rank1 < (len(self.matrix[0]) - 1):
94 | print("Hệ PT có vô số nghiệm...Niệm!")
95 | self.display_solutions()
96 | else:
97 | print("Hệ PT có nghiệm duy nhất!")
98 | self.display_solutions()
99 | # solutions_checker()
100 |
101 | def display_solutions(self):
102 | """Ghi kết quả vào ma trận result, in ma trận result ra màn hình và xuất ra file output.txt"""
103 | # Ghi kết quả vào ma trận result
104 | # global result
105 | for column in range(len(self.matrix[0]) - 1):
106 | if column in self.index_column:
107 | vt = self.index_column.index(column)
108 | self.result[column][0] = self.matrix[self.index_row[vt]][len(self.matrix[0]) - 1]
109 | for i in range(len(self.matrix[0]) - 1):
110 | if i not in self.index_column:
111 | self.result[column][i + 1] = -self.matrix[self.index_row[vt]][i]
112 | else:
113 | self.result[column][column + 1] = 1
114 |
115 | # In ma trận result ra màn hình
116 | print()
117 | print("Nghiệm tìm được: ")
118 | print(self.result[:,0])
119 |
120 | # Xuất kết quả ra file output.txt
121 | np.savetxt(path + 'GJ_output.txt', self.result, fmt='%.5f') # %.5f: lấy 5 chữ số sau dấu phẩy ghi vào file
122 |
123 | # Main program
124 | def main(self):
125 | print(self.matrix)
126 | print("- - - - - - - - - - - - - - - - - - - -")
127 | print()
128 | for i in range(0, min(len(self.matrix), len(self.matrix[0]))):
129 | self.Gauss_Jordan_method()
130 | print(self.matrix)
131 | print("- - - - - - - - - - - - - - - - - - - -")
132 | # print("- - - - - Chuẩn hóa hệ số - - - - -")
133 | self.normalize_pivot_element()
134 | print("- - - - - Kết luận - - - - -")
135 | self.rank()
136 | print()
137 | print("Kiểm tra nghiệm A*x = ", self.A@self.result[:,0].T)
138 |
139 | try:
140 | RUN = Gauss_Jordan_Algorithms()
141 | RUN.main()
142 | except:
143 | f = open(path + 'GJ_output.txt', "w")
144 | f.write("Lỗi!")
145 | f.close()
146 |
147 |
--------------------------------------------------------------------------------
/Min_max/min_max.py:
--------------------------------------------------------------------------------
1 |
2 | delta = 1e-7
3 | eta = 1e-5
4 |
5 | def f(x):
6 | return 2*x**5 - 12*x**4 + 3*x**2 - 15
7 |
8 |
9 | def df(x):
10 | return (f(x + delta) - f(x - delta)) / (2 * delta)
11 |
12 |
13 | def symmetry_df(x):
14 | return -df(x)
15 |
16 |
17 |
18 | def gradient_descent(a, b):
19 | x_ct = a
20 | count = 1
21 | while (not (abs(df(x_ct)) < delta)):
22 | x_ct = x_ct - eta * df(x_ct)
23 | count += 1
24 | if count > 1e+7:
25 | break
26 | if x_ct > b:
27 | print("Hàm đơn điệu trên (", a, " , ", b, ")")
28 | return x_ct
29 | elif x_ct < a:
30 | # print("Hàm đang có xu hướng tăng -> tìm cực đại")
31 | return x_ct
32 | return x_ct
33 |
34 |
35 | def gradient_descent_symmetry(a, b):
36 | x_cd = a
37 | count = 0
38 | while (not (abs(symmetry_df(x_cd)) < delta)):
39 | x_cd = x_cd - eta * symmetry_df(x_cd)
40 | count += 1
41 | if count > 1e+6:
42 | break
43 | if x_cd > b:
44 | print("Hàm đơn điệu trên (", a, ",", b, ")")
45 | return x_cd
46 | elif x_cd < a:
47 | # print("Hàm đang có xu hướng giảm -> tìm cực tiểu.")
48 | return x_cd
49 | return x_cd
50 |
51 |
52 | def find_Extreme_of_theFuntion(a, b):
53 | global count1
54 | global count2
55 | while True:
56 | temp1 = gradient_descent(a, b)
57 | temp2 = gradient_descent_symmetry(a, b)
58 | if (temp1 > b and temp2 < a) or (temp1 < a and temp2 > b):
59 | break
60 | if (temp1 > a) and (temp1 < b):
61 | x_ct.append(temp1)
62 | a = x_ct[count1] + 0.05
63 | count1 += 1
64 |
65 | if (temp2 > a):
66 | if (temp2 < b):
67 | x_cd.append(temp2)
68 | a = x_cd[count2] + 0.05
69 | count2 += 1
70 | print("Cực tiểu: ", x_ct[2:])
71 | print("Cực đại: ", x_cd[2:])
72 |
73 |
74 | if __name__ == '__main__':
75 | a = float(input("Nhap a: "))
76 | b = float(input("Nhap b: "))
77 | count1: int = 2
78 | count2: int = 2
79 | x_ct = [a, b]
80 | x_cd = [a, b]
81 | find_Extreme_of_theFuntion(a, b)
82 | # Tìm min của hàm số:
83 | x_min = a
84 | for i in x_ct:
85 | if f(i) < f(x_min):
86 | x_min = i
87 | # Tìm max của hàm số:
88 | x_max = a
89 | for i in x_cd:
90 | if f(i) > f(x_max):
91 | x_max = i
92 | print("Giá trị nhỏ nhất của hàm số trên đoạn: f(", round(x_min, 3), ") = ", f(x_min))
93 | print("Giá trị lớn nhất của hàm số trên đoạn: f(", round(x_max, 3), ") = ", f(x_max))
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Numeric-Analysis-Code
2 |
3 | ## Đối với bài toán F(x) = 0
4 | Sửa hàm số f(x) (và g(x) đối với phương pháp lặp đơn) và nhập khoảng tìm nghiệm theo hướng dẫn của chương trình. Các kết quả từng vòng lặp có in cụ thể ra file output tương ứng.
5 |
6 | ## Đối với bài toán giải hệ phương trình Ax = b
7 | Nhập input cả A, b vào cùng file và cùng hàng với nhau luôn, ví dụ:
8 |
9 | 2x + y + z = 8
10 |
11 | x + y - 2z = -2
12 |
13 | x + 2y + z = 2
14 |
15 | thì sẽ nhập:
16 |
17 | 2 1 1 8
18 |
19 | 1 1 -2 -2
20 |
21 | 1 2 1 2
22 |
--------------------------------------------------------------------------------
/dinhthuc/A.txt:
--------------------------------------------------------------------------------
1 | 1 3 1 4 -3 4
2 | 4 12 1 2 5 6
3 | -1 2 5 1 4 7
4 | 4 12 1 2 6 1
5 | 2 3 4 5 8 6
6 | -1 8 -6 -3 -7 21
--------------------------------------------------------------------------------
/dinhthuc/gauss_method.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import sys
3 |
4 | data = np.genfromtxt('A.txt', delimiter=' ')
5 | A = np.array(data)
6 | print("A = ", A)
7 |
8 | n = len(A[0])
9 | i = 0
10 | detA = 1
11 | temp = np.zeros((1, n))
12 |
13 | while i < n:
14 | check = -1
15 | for r in range(i, n):
16 | if np.abs(A[r, i]) == 1:
17 | check = 1
18 | break
19 | if check == -1:
20 | Any = np.abs(A[i, i])
21 | r = i
22 | for k in range(i+1, n):
23 | if np.abs(A[k, i]) > Any:
24 | Any = np.abs(A[k, i])
25 | r = k
26 | if Any == 0:
27 | print("Cột thứ ", i+1, " của ma trận A(", i,") đồng nhất 0")
28 | print("detA = 0")
29 | sys.exit()
30 | if r != i:
31 | temp[0] = A[i]
32 | A[i] = A[r]
33 | A[r] = temp[0]
34 | detA = -detA
35 | print()
36 | print("Đổi chỗ hàng thứ ", i + 1, " với hàng thứ ", r + 1)
37 |
38 | for j in range(i + 1, n):
39 | if j < n:
40 | p = A[j, i] / A[i, i]
41 | A[j] = A[j] - p * A[i]
42 | print()
43 | print("Lần lặp thứ: ",i+1)
44 | print(A)
45 | i += 1
46 |
47 | for i in range(n):
48 | detA = detA * A[i, i]
49 | print("Định thức của ma trận A là: ", detA)
50 |
--------------------------------------------------------------------------------