matrix-ops-calc 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: matrix-ops-calc
3
+ Version: 0.1.0
4
+ Summary: 矩阵初等行变换、矩阵乘法与行最简形计算器
5
+ Requires-Python: >=3.10
@@ -0,0 +1,251 @@
1
+ """矩阵计算器:支持初等行变换、矩阵乘法,并能化为行最简形。
2
+
3
+ 所有元素使用 Fraction 精确计算,输入支持整数、小数和分数(如 2、-0.5、1/3)。
4
+ """
5
+
6
+ from fractions import Fraction
7
+
8
+ Matrix = list[list[Fraction]]
9
+
10
+
11
+ def swap_rows(a: Matrix, i: int, j: int) -> Matrix:
12
+ """交换第 i 行和第 j 行(下标从 0 开始)。"""
13
+ a[i], a[j] = a[j], a[i]
14
+ return a
15
+
16
+
17
+ def scale_row(a: Matrix, i: int, k: Fraction) -> Matrix:
18
+ """第 i 行的所有元素乘以非零常数 k。"""
19
+ if k == 0:
20
+ raise ValueError("倍数 k 不能为 0")
21
+ a[i] = [k * x for x in a[i]]
22
+ return a
23
+
24
+
25
+ def add_scaled_row(a: Matrix, target: int, source: int, k: Fraction) -> Matrix:
26
+ """把第 source 行的 k 倍加到第 target 行:R_target += k * R_source。"""
27
+ a[target] = [x + k * y for x, y in zip(a[target], a[source])]
28
+ return a
29
+
30
+
31
+ def matmul(a: Matrix, b: Matrix) -> Matrix:
32
+ """矩阵乘法 A × B,要求 A 的列数等于 B 的行数。"""
33
+ if len(a[0]) != len(b):
34
+ raise ValueError(
35
+ f"维度不匹配:A 是 {len(a)}×{len(a[0])},B 是 {len(b)}×{len(b[0])}"
36
+ )
37
+ # 结果第 i 行第 j 列 = A 的第 i 行与 B 的第 j 列对应元素乘积之和
38
+ return [
39
+ [sum(a[i][k] * b[k][j] for k in range(len(b))) for j in range(len(b[0]))]
40
+ for i in range(len(a))
41
+ ]
42
+
43
+
44
+ def to_rref(a: Matrix) -> tuple[Matrix, list[tuple[str, Matrix]]]:
45
+ """用初等行变换把矩阵化为行最简形,并记录每一步的操作和结果。"""
46
+ m = [row[:] for row in a]
47
+ row_count, col_count = len(m), len(m[0])
48
+ steps: list[tuple[str, Matrix]] = []
49
+ pivot_row = 0
50
+
51
+ for col in range(col_count):
52
+ if pivot_row >= row_count:
53
+ break
54
+
55
+ # 在当前列中找第一个非零元素作为主元
56
+ pivot = None
57
+ for r in range(pivot_row, row_count):
58
+ if m[r][col] != 0:
59
+ pivot = r
60
+ break
61
+ if pivot is None:
62
+ continue
63
+
64
+ # 把主元换到当前行
65
+ if pivot != pivot_row:
66
+ swap_rows(m, pivot, pivot_row)
67
+ steps.append(
68
+ (f"交换第 {pivot + 1} 行和第 {pivot_row + 1} 行", [row[:] for row in m])
69
+ )
70
+
71
+ # 把主元化为 1
72
+ factor = m[pivot_row][col]
73
+ if factor != 1:
74
+ scale_row(m, pivot_row, Fraction(1) / factor)
75
+ steps.append(
76
+ (f"第 {pivot_row + 1} 行除以 {format_fraction(factor)}", [row[:] for row in m])
77
+ )
78
+
79
+ # 用主元行消去该列其余所有行(上方和下方)
80
+ for r in range(row_count):
81
+ if r == pivot_row or m[r][col] == 0:
82
+ continue
83
+ k = -m[r][col]
84
+ add_scaled_row(m, r, pivot_row, k)
85
+ steps.append(
86
+ (
87
+ f"第 {r + 1} 行加上第 {pivot_row + 1} 行的 {format_fraction(k)} 倍",
88
+ [row[:] for row in m],
89
+ )
90
+ )
91
+
92
+ pivot_row += 1
93
+
94
+ return [row[:] for row in m], steps
95
+
96
+
97
+ def format_fraction(x: Fraction) -> str:
98
+ """整数显示为 3,分数显示为 3/2 或 -1/3。"""
99
+ if x.denominator == 1:
100
+ return str(x.numerator)
101
+ return f"{x.numerator}/{x.denominator}"
102
+
103
+
104
+ def print_matrix(a: Matrix, name: str = "结果") -> None:
105
+ print(f"{name}({len(a)}×{len(a[0])}):")
106
+ for row in a:
107
+ print(" " + " ".join(format_fraction(x) for x in row))
108
+ print()
109
+
110
+
111
+ # ---------------- 输入辅助函数 ----------------
112
+
113
+ def read_int(prompt: str) -> int:
114
+ """反复提示,直到用户输入一个整数。"""
115
+ while True:
116
+ try:
117
+ return int(input(prompt).strip())
118
+ except ValueError:
119
+ print("请输入整数。")
120
+
121
+
122
+ def read_positive_int(prompt: str) -> int:
123
+ """反复提示,直到用户输入一个正整数。"""
124
+ while True:
125
+ value = read_int(prompt)
126
+ if value > 0:
127
+ return value
128
+ print("请输入大于 0 的整数。")
129
+
130
+
131
+ def read_fraction(prompt: str) -> Fraction:
132
+ """反复提示,直到用户输入一个数字或分数。"""
133
+ while True:
134
+ try:
135
+ return Fraction(input(prompt).strip())
136
+ except (ValueError, ZeroDivisionError):
137
+ print("请输入数字或分数(如 2、-0.5、1/3)。")
138
+
139
+
140
+ def read_row_index(prompt: str, row_count: int) -> int:
141
+ """读取 1 开始的行号并转换为 0 开始的内部下标。"""
142
+ while True:
143
+ index = read_int(prompt)
144
+ if 1 <= index <= row_count:
145
+ return index - 1
146
+ print(f"行号必须在 1~{row_count} 之间。")
147
+
148
+
149
+ def read_matrix(name: str) -> Matrix:
150
+ """按行列数逐行读取一个矩阵,元素可以是整数、小数或分数。"""
151
+ rows = read_positive_int(f"矩阵 {name} 的行数:")
152
+ cols = read_positive_int(f"矩阵 {name} 的列数:")
153
+ print(f"请依次输入 {rows} 行,每行 {cols} 个数,用空格分隔(支持 1/2 这样的分数):")
154
+
155
+ matrix: Matrix = []
156
+ for i in range(rows):
157
+ while True:
158
+ parts = input(f"第 {i + 1} 行:").split()
159
+ if len(parts) != cols:
160
+ print(f"本行需要 {cols} 个数,请重新输入。")
161
+ continue
162
+ try:
163
+ matrix.append([Fraction(x) for x in parts])
164
+ break
165
+ except (ValueError, ZeroDivisionError):
166
+ print("存在无法识别的数字或分数,请重新输入。")
167
+ print()
168
+ return matrix
169
+
170
+
171
+ # ---------------- 主程序 ----------------
172
+
173
+ def main() -> None:
174
+ menu = (
175
+ "\n========== 矩阵计算器 ==========\n"
176
+ "1. 交换两行\n"
177
+ "2. 某一行乘以一个非零数\n"
178
+ "3. 把某行的 k 倍加到另一行\n"
179
+ "4. 矩阵乘法\n"
180
+ "5. 化为行最简形(RREF)\n"
181
+ "0. 退出\n"
182
+ "================================"
183
+ )
184
+
185
+ while True:
186
+ print(menu)
187
+ choice = input("请选择操作(0~5):").strip()
188
+
189
+ if choice == "0":
190
+ print("已退出。")
191
+ break
192
+
193
+ elif choice == "1":
194
+ a = read_matrix("A")
195
+ print_matrix(a, "原矩阵 A")
196
+ i = read_row_index(f"请输入第 1 个行号(1~{len(a)}):", len(a))
197
+ j = read_row_index(f"请输入第 2 个行号(1~{len(a)}):", len(a))
198
+ swap_rows(a, i, j)
199
+ print_matrix(a, "交换后的矩阵")
200
+
201
+ elif choice == "2":
202
+ a = read_matrix("A")
203
+ print_matrix(a, "原矩阵 A")
204
+ i = read_row_index(f"请输入要乘的行号(1~{len(a)}):", len(a))
205
+ k = read_fraction("请输入非零乘数 k:")
206
+ while k == 0:
207
+ print("k 不能为 0,请重新输入。")
208
+ k = read_fraction("请输入非零乘数 k:")
209
+ scale_row(a, i, k)
210
+ print_matrix(a, f"第 {i + 1} 行乘以 {format_fraction(k)} 后的矩阵")
211
+
212
+ elif choice == "3":
213
+ a = read_matrix("A")
214
+ print_matrix(a, "原矩阵 A")
215
+ target = read_row_index(f"请输入目标行号(1~{len(a)}):", len(a))
216
+ source = read_row_index(f"请输入被加行号(1~{len(a)}):", len(a))
217
+ k = read_fraction("请输入倍数 k:")
218
+ add_scaled_row(a, target, source, k)
219
+ print_matrix(
220
+ a,
221
+ f"第 {target + 1} 行加上第 {source + 1} 行的 {format_fraction(k)} 倍",
222
+ )
223
+
224
+ elif choice == "4":
225
+ a = read_matrix("A")
226
+ b = read_matrix("B")
227
+ try:
228
+ result = matmul(a, b)
229
+ except ValueError as error:
230
+ print(f"无法相乘:{error}\n")
231
+ else:
232
+ print_matrix(result, "A × B")
233
+
234
+ elif choice == "5":
235
+ a = read_matrix("A")
236
+ print_matrix(a, "原矩阵 A")
237
+ result, steps = to_rref(a)
238
+ if not steps:
239
+ print("该矩阵已经是行最简形。\n")
240
+ else:
241
+ for index, (description, snapshot) in enumerate(steps, 1):
242
+ print(f"第 {index} 步:{description}")
243
+ print_matrix(snapshot, "矩阵")
244
+ print_matrix(result, "最终行最简形")
245
+
246
+ else:
247
+ print("无效选项,请输入 0~5 之间的数字。")
248
+
249
+
250
+ if __name__ == "__main__":
251
+ main()
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.4
2
+ Name: matrix-ops-calc
3
+ Version: 0.1.0
4
+ Summary: 矩阵初等行变换、矩阵乘法与行最简形计算器
5
+ Requires-Python: >=3.10
@@ -0,0 +1,7 @@
1
+ matrix_ops.py
2
+ pyproject.toml
3
+ matrix_ops_calc.egg-info/PKG-INFO
4
+ matrix_ops_calc.egg-info/SOURCES.txt
5
+ matrix_ops_calc.egg-info/dependency_links.txt
6
+ matrix_ops_calc.egg-info/entry_points.txt
7
+ matrix_ops_calc.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ matrix-ops = matrix_ops:main
@@ -0,0 +1,15 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "matrix-ops-calc"
7
+ version = "0.1.0"
8
+ description = "矩阵初等行变换、矩阵乘法与行最简形计算器"
9
+ requires-python = ">=3.10"
10
+
11
+ [project.scripts]
12
+ matrix-ops = "matrix_ops:main"
13
+
14
+ [tool.setuptools]
15
+ py-modules = ["matrix_ops"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+