is-calc 0.1.0__py3-none-any.whl
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.
- is_calc-0.1.0.dist-info/METADATA +87 -0
- is_calc-0.1.0.dist-info/RECORD +6 -0
- is_calc-0.1.0.dist-info/WHEEL +5 -0
- is_calc-0.1.0.dist-info/licenses/LICENSE +21 -0
- is_calc-0.1.0.dist-info/top_level.txt +1 -0
- is_calc.py +523 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: is-calc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A small calculator library with vector/matrix helpers, determinant, adjugate and inverse.
|
|
5
|
+
Author-email: illusionhs <illusionhs@163.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: calculator,matrix,determinant,adjugate,inverse,linear-algebra
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Education
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
19
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# is-calc
|
|
23
|
+
|
|
24
|
+
A tiny, dependency-free calculator library: scalar helpers plus `Vector` and
|
|
25
|
+
`Matrix` classes with transpose, determinant, minor, cofactor, adjugate and
|
|
26
|
+
inverse.
|
|
27
|
+
|
|
28
|
+
> **Warning**
|
|
29
|
+
> This package was written for practice and is not proved to be complete.
|
|
30
|
+
> Do not use it in production.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
python -m pip install dist/is_calc-0.1.0-py3-none-any.whl
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Quick start
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from is_calc import Matrix, Vector, gcd, lcm
|
|
42
|
+
|
|
43
|
+
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
|
|
44
|
+
A.determinant() # -3
|
|
45
|
+
A.minor(0, 2) # Matrix([[4, 5], [7, 8]])
|
|
46
|
+
A.cofactor_matrix()
|
|
47
|
+
A.adjugate() # also .adj() / .adjoint()
|
|
48
|
+
A.inverse() # also .inv(); raises ValueError if singular
|
|
49
|
+
A.transpose() # also .T
|
|
50
|
+
A @ A.inverse() # identity (float rounding aside)
|
|
51
|
+
A.det() # short form of determinant()
|
|
52
|
+
|
|
53
|
+
B = Matrix([[2, 1], [1, 3]])
|
|
54
|
+
B * 2 # scalar multiplication
|
|
55
|
+
B / 2 # scalar division
|
|
56
|
+
|
|
57
|
+
u = Vector([1, 2, 3])
|
|
58
|
+
v = Vector([4, 5, 6])
|
|
59
|
+
u + v, u.dot(v), u.modulus
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`Matrix.dim` is a `(rows, columns)` tuple. Integer matrices get an exact
|
|
63
|
+
integer determinant (fraction-free Bareiss elimination); float, `Fraction`
|
|
64
|
+
and complex matrices use Gaussian elimination with partial pivoting.
|
|
65
|
+
`inverse()` performs a true division, so the entries of an integer matrix
|
|
66
|
+
become floats.
|
|
67
|
+
|
|
68
|
+
## Run the built-in self test
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
python is_calc.py
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
python -m venv .venv
|
|
78
|
+
.venv\Scripts\activate # Windows
|
|
79
|
+
# source .venv/bin/activate # Linux / macOS
|
|
80
|
+
python -m pip install -e ".[dev]"
|
|
81
|
+
python -m build
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Build artifacts are written to `dist/`:
|
|
85
|
+
|
|
86
|
+
* `is_calc-0.1.0-py3-none-any.whl` — wheel (install with pip)
|
|
87
|
+
* `is_calc-0.1.0.tar.gz` — source distribution
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
is_calc.py,sha256=aN351Ep5rM2ffPx-dSIj7uHc9K0rf-cPfmMa7WbB3Yk,18414
|
|
2
|
+
is_calc-0.1.0.dist-info/licenses/LICENSE,sha256=0XyJ7AHD8rin6xYyQTc9ye8ydIrokLssXtd2oNxsNCA,1086
|
|
3
|
+
is_calc-0.1.0.dist-info/METADATA,sha256=joMTb8Qdj8YNVC_ipt4kmrcWi8TgIqwXqy_LRe9kgZA,2670
|
|
4
|
+
is_calc-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
is_calc-0.1.0.dist-info/top_level.txt,sha256=iV0ZRdUlK-vt9-Q2Mg6JWVYHEbCzEPvta-YlamkB2lY,8
|
|
6
|
+
is_calc-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 illusionhs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
is_calc
|
is_calc.py
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
"""
|
|
2
|
+
<libname>
|
|
3
|
+
is_calc
|
|
4
|
+
|
|
5
|
+
<description>
|
|
6
|
+
A small library includes some basic calculate and linear algebra function.
|
|
7
|
+
|
|
8
|
+
<warning>
|
|
9
|
+
The library is just for test, the functions are not proved to be complete.
|
|
10
|
+
Do not use it in production.
|
|
11
|
+
May be incompatible with standard library function, please use it with caution.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
# Keep this in sync with the ``version`` field in pyproject.toml.
|
|
15
|
+
__version__ = "0.1.0"
|
|
16
|
+
|
|
17
|
+
# Thin wrappers around the basic arithmetic operators, kept as plain functions
|
|
18
|
+
# so they can be used in the same style as the rest of the module. Note that
|
|
19
|
+
# pow/div/mod/floor_div shadow the corresponding builtins inside this module on
|
|
20
|
+
# purpose; import with care (see the warning above).
|
|
21
|
+
def add(a, b):
|
|
22
|
+
return a + b
|
|
23
|
+
|
|
24
|
+
def sub(a, b):
|
|
25
|
+
return a - b
|
|
26
|
+
|
|
27
|
+
def mul(a, b):
|
|
28
|
+
return a * b
|
|
29
|
+
|
|
30
|
+
def div(a, b):
|
|
31
|
+
if b == 0:
|
|
32
|
+
raise ZeroDivisionError("division by zero")
|
|
33
|
+
return a / b
|
|
34
|
+
|
|
35
|
+
def pow(a, b):
|
|
36
|
+
return a ** b
|
|
37
|
+
|
|
38
|
+
def mod(a, b):
|
|
39
|
+
if b == 0:
|
|
40
|
+
raise ZeroDivisionError("integer modulo by zero")
|
|
41
|
+
return a % b
|
|
42
|
+
|
|
43
|
+
def floor_div(a, b):
|
|
44
|
+
if b == 0:
|
|
45
|
+
raise ZeroDivisionError("integer division or modulo by zero")
|
|
46
|
+
return a // b
|
|
47
|
+
|
|
48
|
+
def gcd(a,b):
|
|
49
|
+
"""Return the greatest common divisor of a and b (never negative)."""
|
|
50
|
+
# Euclid's algorithm, iterative; abs() keeps it correct for negatives.
|
|
51
|
+
a, b = abs(a), abs(b)
|
|
52
|
+
while b:
|
|
53
|
+
a, b = b, a % b
|
|
54
|
+
return a
|
|
55
|
+
|
|
56
|
+
def lcm(a, b):
|
|
57
|
+
"""Return the least common multiple of a and b; lcm(0, x) is 0."""
|
|
58
|
+
# Guard the zero case: gcd(0, 0) == 0 would make the division below fail.
|
|
59
|
+
if a == 0 or b == 0:
|
|
60
|
+
return 0
|
|
61
|
+
return abs(a * b) // gcd(a, b)
|
|
62
|
+
|
|
63
|
+
class Vector:
|
|
64
|
+
"""A small n-dimensional vector backed by a plain list.
|
|
65
|
+
|
|
66
|
+
``dim`` is inferred from ``v``; pass only ``dim`` to build a zero vector.
|
|
67
|
+
"""
|
|
68
|
+
def __init__(self, v: list = None, dim: int = None):
|
|
69
|
+
if v is None:
|
|
70
|
+
if dim is None:
|
|
71
|
+
raise ValueError("either v or dim must be given")
|
|
72
|
+
v = [0] * dim
|
|
73
|
+
v = list(v)
|
|
74
|
+
if dim is not None and dim != len(v):
|
|
75
|
+
raise ValueError("dim must match the length of v")
|
|
76
|
+
self.dim = len(v)
|
|
77
|
+
self.v = v
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def modulus(self):
|
|
81
|
+
"""Euclidean norm of the vector."""
|
|
82
|
+
return sum(x**2 for x in self.v) ** 0.5
|
|
83
|
+
|
|
84
|
+
def __getitem__(self, index):
|
|
85
|
+
return self.v[index]
|
|
86
|
+
|
|
87
|
+
def __setitem__(self, index, value):
|
|
88
|
+
self.v[index] = value
|
|
89
|
+
|
|
90
|
+
def __str__(self):
|
|
91
|
+
return f"Vector({self.v})"
|
|
92
|
+
|
|
93
|
+
def __repr__(self):
|
|
94
|
+
return self.__str__()
|
|
95
|
+
|
|
96
|
+
def __len__(self):
|
|
97
|
+
return self.dim
|
|
98
|
+
|
|
99
|
+
def __add__(self, other):
|
|
100
|
+
if not isinstance(other, Vector):
|
|
101
|
+
raise TypeError("can only add Vector to Vector")
|
|
102
|
+
if len(self) != len(other):
|
|
103
|
+
raise ValueError("vector dimension must be the same")
|
|
104
|
+
return Vector([self[i] + other[i] for i in range(len(self))], self.dim)
|
|
105
|
+
|
|
106
|
+
def __sub__(self, other):
|
|
107
|
+
if not isinstance(other, Vector):
|
|
108
|
+
raise TypeError("can only subtract Vector from Vector")
|
|
109
|
+
if len(self) != len(other):
|
|
110
|
+
raise ValueError("vector dimension must be the same")
|
|
111
|
+
return Vector([self[i] - other[i] for i in range(len(self))], self.dim)
|
|
112
|
+
|
|
113
|
+
def __mul__(self, scalar):
|
|
114
|
+
"""Scalar multiplication (use dot() for the dot product)."""
|
|
115
|
+
if isinstance(scalar, Vector):
|
|
116
|
+
raise TypeError("Vector * Vector is not defined, use dot() instead")
|
|
117
|
+
return Vector([self[i] * scalar for i in range(len(self))], self.dim)
|
|
118
|
+
|
|
119
|
+
def __rmul__(self, scalar):
|
|
120
|
+
return self.__mul__(scalar)
|
|
121
|
+
|
|
122
|
+
def __truediv__(self, scalar):
|
|
123
|
+
if scalar == 0:
|
|
124
|
+
raise ZeroDivisionError("vector division by zero")
|
|
125
|
+
return Vector([self[i] / scalar for i in range(len(self))], self.dim)
|
|
126
|
+
|
|
127
|
+
def dot(self, other):
|
|
128
|
+
"""Return the dot product self . other."""
|
|
129
|
+
if not isinstance(other, Vector):
|
|
130
|
+
raise TypeError("dot() expects a Vector")
|
|
131
|
+
if len(self) != len(other):
|
|
132
|
+
raise ValueError("vector dimension must be the same")
|
|
133
|
+
return sum(self[i] * other[i] for i in range(len(self)))
|
|
134
|
+
|
|
135
|
+
def __eq__(self, other):
|
|
136
|
+
if not isinstance(other, Vector):
|
|
137
|
+
return False
|
|
138
|
+
if len(self) != len(other):
|
|
139
|
+
return False
|
|
140
|
+
return all(self[i] == other[i] for i in range(len(self)))
|
|
141
|
+
|
|
142
|
+
class Matrix:
|
|
143
|
+
"""Row-major matrix.
|
|
144
|
+
|
|
145
|
+
``dim`` is a ``(rows, columns)`` tuple, and ``m`` is a list of rows.
|
|
146
|
+
|
|
147
|
+
Determinant related helpers (all square matrices only unless stated):
|
|
148
|
+
|
|
149
|
+
* ``minor(i, j)`` -> submatrix with row ``i`` and column ``j`` removed
|
|
150
|
+
* ``cofactor(i, j)`` -> signed determinant of that submatrix
|
|
151
|
+
* ``cofactor_matrix()`` -> matrix of all cofactors
|
|
152
|
+
* ``adjugate()`` -> transpose of the cofactor matrix (aka adjoint)
|
|
153
|
+
* ``determinant()`` -> scalar
|
|
154
|
+
* ``inverse()`` -> Matrix, raises ``ValueError`` if singular
|
|
155
|
+
|
|
156
|
+
Every function that produces a matrix returns a new ``Matrix`` object.
|
|
157
|
+
"""
|
|
158
|
+
def __init__(self, m: list = None, dim: tuple = None):
|
|
159
|
+
if m is None:
|
|
160
|
+
if dim is None:
|
|
161
|
+
raise ValueError("either m or dim must be given")
|
|
162
|
+
rows, cols = dim
|
|
163
|
+
m = [[0] * cols for _ in range(rows)]
|
|
164
|
+
else:
|
|
165
|
+
m = [list(row) for row in m]
|
|
166
|
+
rows = len(m)
|
|
167
|
+
cols = len(m[0]) if rows else 0
|
|
168
|
+
for row in m:
|
|
169
|
+
if len(row) != cols:
|
|
170
|
+
raise ValueError("matrix rows must have the same length")
|
|
171
|
+
if dim is not None and tuple(dim) != (rows, cols):
|
|
172
|
+
raise ValueError(
|
|
173
|
+
f"dim {tuple(dim)} does not match data shape {(rows, cols)}")
|
|
174
|
+
self.m = m
|
|
175
|
+
self.dim = (rows, cols)
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def rows(self):
|
|
179
|
+
return self.dim[0]
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def cols(self):
|
|
183
|
+
return self.dim[1]
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def shape(self):
|
|
187
|
+
return self.dim
|
|
188
|
+
|
|
189
|
+
def copy(self):
|
|
190
|
+
"""Return a shallow copy (the rows are copied, the values are shared)."""
|
|
191
|
+
return type(self)(self.m)
|
|
192
|
+
|
|
193
|
+
def __getitem__(self, key):
|
|
194
|
+
# m[i, j] -> single element; m[i] / m[i:j] -> whole row(s).
|
|
195
|
+
if isinstance(key, tuple):
|
|
196
|
+
if len(key) != 2:
|
|
197
|
+
raise TypeError("Matrix expects a (row, column) tuple")
|
|
198
|
+
i, j = key
|
|
199
|
+
if not isinstance(i, int) or not isinstance(j, int):
|
|
200
|
+
raise TypeError("Matrix indices must be integers")
|
|
201
|
+
return self.m[i][j]
|
|
202
|
+
elif isinstance(key, slice):
|
|
203
|
+
return self.m[key]
|
|
204
|
+
elif isinstance(key, int):
|
|
205
|
+
return self.m[key]
|
|
206
|
+
else:
|
|
207
|
+
raise TypeError("Matrix indices must be integers or slices/tuples of integers")
|
|
208
|
+
|
|
209
|
+
def __setitem__(self, key, value):
|
|
210
|
+
if isinstance(key, tuple):
|
|
211
|
+
if len(key) != 2:
|
|
212
|
+
raise TypeError("Matrix expects a (row, column) tuple")
|
|
213
|
+
i,j=key
|
|
214
|
+
self.m[i][j] = value
|
|
215
|
+
elif isinstance(key, slice):
|
|
216
|
+
self.m[key] = value
|
|
217
|
+
elif isinstance(key, int):
|
|
218
|
+
self.m[key] = value
|
|
219
|
+
else:
|
|
220
|
+
raise TypeError("Matrix indices must be integers or slices/tuples of integers")
|
|
221
|
+
|
|
222
|
+
def __str__(self):
|
|
223
|
+
return f"Matrix({self.m})"
|
|
224
|
+
|
|
225
|
+
def __repr__(self):
|
|
226
|
+
return self.__str__()
|
|
227
|
+
|
|
228
|
+
def __len__(self):
|
|
229
|
+
return self.rows
|
|
230
|
+
|
|
231
|
+
def __iter__(self):
|
|
232
|
+
"""Iterate over the entries row by row (flattened, len is the row count)."""
|
|
233
|
+
for row in self.m:
|
|
234
|
+
for value in row:
|
|
235
|
+
yield value
|
|
236
|
+
|
|
237
|
+
def _check_same_shape(self, other, op):
|
|
238
|
+
if not isinstance(other, Matrix):
|
|
239
|
+
raise TypeError(
|
|
240
|
+
f"unsupported operand type(s) for {op}: "
|
|
241
|
+
f"'Matrix' and '{type(other).__name__}'")
|
|
242
|
+
if self.dim != other.dim:
|
|
243
|
+
raise ValueError("Matrix dimension must be the same")
|
|
244
|
+
|
|
245
|
+
def __add__(self, other):
|
|
246
|
+
self._check_same_shape(other, "+")
|
|
247
|
+
return Matrix([[a + b for a, b in zip(r1, r2)]
|
|
248
|
+
for r1, r2 in zip(self.m, other.m)])
|
|
249
|
+
|
|
250
|
+
def __sub__(self, other):
|
|
251
|
+
self._check_same_shape(other, "-")
|
|
252
|
+
return Matrix([[a - b for a, b in zip(r1, r2)]
|
|
253
|
+
for r1, r2 in zip(self.m, other.m)])
|
|
254
|
+
|
|
255
|
+
def __neg__(self):
|
|
256
|
+
return Matrix([[-x for x in row] for row in self.m])
|
|
257
|
+
|
|
258
|
+
def __mul__(self, scalar):
|
|
259
|
+
if isinstance(scalar, Matrix):
|
|
260
|
+
raise TypeError("use '@' for matrix multiplication")
|
|
261
|
+
return Matrix([[x * scalar for x in row] for row in self.m])
|
|
262
|
+
|
|
263
|
+
def __rmul__(self, scalar):
|
|
264
|
+
return self.__mul__(scalar)
|
|
265
|
+
|
|
266
|
+
def __truediv__(self, scalar):
|
|
267
|
+
if isinstance(scalar, Matrix):
|
|
268
|
+
raise TypeError("use '@' with inverse() for matrix division")
|
|
269
|
+
if scalar == 0:
|
|
270
|
+
raise ZeroDivisionError("matrix division by zero")
|
|
271
|
+
return Matrix([[x / scalar for x in row] for row in self.m])
|
|
272
|
+
|
|
273
|
+
def __matmul__(self, other):
|
|
274
|
+
"""Matrix product: ``A @ B``."""
|
|
275
|
+
if not isinstance(other, Matrix):
|
|
276
|
+
return NotImplemented
|
|
277
|
+
if self.cols != other.rows:
|
|
278
|
+
raise ValueError(
|
|
279
|
+
f"cannot multiply {(self.rows, self.cols)} by {(other.rows, other.cols)}")
|
|
280
|
+
return Matrix([[sum(self.m[i][k] * other.m[k][j]
|
|
281
|
+
for k in range(self.cols))
|
|
282
|
+
for j in range(other.cols)]
|
|
283
|
+
for i in range(self.rows)])
|
|
284
|
+
|
|
285
|
+
def __eq__(self, other):
|
|
286
|
+
if not isinstance(other, Matrix):
|
|
287
|
+
return False
|
|
288
|
+
if self.dim != other.dim:
|
|
289
|
+
return False
|
|
290
|
+
return all(self[i][j] == other[i][j] for i in range(len(self.m)) for j in range(len(self.m[i])))
|
|
291
|
+
|
|
292
|
+
def is_square(self):
|
|
293
|
+
"""Return True when the matrix has as many rows as columns."""
|
|
294
|
+
return self.rows == self.cols
|
|
295
|
+
|
|
296
|
+
def _check_square(self, what):
|
|
297
|
+
# Shared guard for determinant / cofactor / inverse style methods.
|
|
298
|
+
if not self.is_square():
|
|
299
|
+
raise ValueError(f"{what} is only defined for square matrices")
|
|
300
|
+
|
|
301
|
+
def transpose(self):
|
|
302
|
+
"""Return the transposed matrix (works for any shape, returns a Matrix)."""
|
|
303
|
+
return type(self)([[self.m[i][j] for i in range(self.rows)]
|
|
304
|
+
for j in range(self.cols)])
|
|
305
|
+
|
|
306
|
+
# ``T`` is a handy alias for transpose().
|
|
307
|
+
@property
|
|
308
|
+
def T(self):
|
|
309
|
+
return self.transpose()
|
|
310
|
+
|
|
311
|
+
def minor(self, i: int, j: int):
|
|
312
|
+
"""Return the submatrix with row ``i`` and column ``j`` removed."""
|
|
313
|
+
if not (0 <= i < self.rows) or not (0 <= j < self.cols):
|
|
314
|
+
raise IndexError(f"minor index {(i, j)} out of range for {self.dim}")
|
|
315
|
+
return type(self)([[self.m[r][c] for c in range(self.cols) if c != j]
|
|
316
|
+
for r in range(self.rows) if r != i])
|
|
317
|
+
|
|
318
|
+
def cofactor(self, i: int, j: int):
|
|
319
|
+
"""Return the signed minor ``(-1) ** (i + j) * det(minor(i, j))``."""
|
|
320
|
+
self._check_square("cofactor")
|
|
321
|
+
sign = -1 if (i + j) % 2 else 1
|
|
322
|
+
return sign * self.minor(i, j).determinant()
|
|
323
|
+
|
|
324
|
+
def cofactor_matrix(self):
|
|
325
|
+
"""Return the matrix whose ``(i, j)`` entry is ``cofactor(i, j)``."""
|
|
326
|
+
self._check_square("cofactor_matrix")
|
|
327
|
+
n = self.rows
|
|
328
|
+
return type(self)([[self.cofactor(i, j) for j in range(n)]
|
|
329
|
+
for i in range(n)])
|
|
330
|
+
|
|
331
|
+
def adjugate(self):
|
|
332
|
+
"""Return the adjugate (adjoint) matrix: ``cofactor_matrix().transpose()``."""
|
|
333
|
+
self._check_square("adjugate")
|
|
334
|
+
return self.cofactor_matrix().transpose()
|
|
335
|
+
|
|
336
|
+
# Common aliases.
|
|
337
|
+
adjoint = adjugate
|
|
338
|
+
adj = adjugate
|
|
339
|
+
|
|
340
|
+
def determinant(self):
|
|
341
|
+
"""Return the determinant.
|
|
342
|
+
|
|
343
|
+
Integer matrices use fraction-free Bareiss elimination, so the result
|
|
344
|
+
stays an exact ``int``. Anything else (float, Fraction, complex, ...)
|
|
345
|
+
uses Gaussian elimination with partial pivoting, which is numerically
|
|
346
|
+
stable.
|
|
347
|
+
"""
|
|
348
|
+
self._check_square("determinant")
|
|
349
|
+
n = self.rows
|
|
350
|
+
if n == 0:
|
|
351
|
+
# 0x0 matrix: det == 1 by convention (needed by minor()).
|
|
352
|
+
return 1
|
|
353
|
+
if n == 1:
|
|
354
|
+
return self.m[0][0]
|
|
355
|
+
if n == 2:
|
|
356
|
+
return self.m[0][0] * self.m[1][1] - self.m[0][1] * self.m[1][0]
|
|
357
|
+
|
|
358
|
+
# Keep exact integer results exact; use floats only for float input.
|
|
359
|
+
if all(isinstance(x, int) for row in self.m for x in row):
|
|
360
|
+
return self._determinant_bareiss()
|
|
361
|
+
return self._determinant_gauss()
|
|
362
|
+
|
|
363
|
+
def _determinant_bareiss(self):
|
|
364
|
+
"""Exact O(n^3) determinant for integer matrices (Bareiss algorithm)."""
|
|
365
|
+
n = self.rows
|
|
366
|
+
a = [row[:] for row in self.m]
|
|
367
|
+
sign = 1
|
|
368
|
+
prev = 1
|
|
369
|
+
for k in range(n - 1):
|
|
370
|
+
if a[k][k] == 0:
|
|
371
|
+
for r in range(k + 1, n):
|
|
372
|
+
if a[r][k] != 0:
|
|
373
|
+
a[k], a[r] = a[r], a[k]
|
|
374
|
+
sign = -sign
|
|
375
|
+
break
|
|
376
|
+
else:
|
|
377
|
+
return 0
|
|
378
|
+
pivot = a[k][k]
|
|
379
|
+
for i in range(k + 1, n):
|
|
380
|
+
for j in range(k + 1, n):
|
|
381
|
+
num = a[i][j] * pivot - a[i][k] * a[k][j]
|
|
382
|
+
# The division is exact, so // keeps the entries integers.
|
|
383
|
+
a[i][j] = num if k == 0 else num // prev
|
|
384
|
+
prev = pivot
|
|
385
|
+
return sign * a[n - 1][n - 1]
|
|
386
|
+
|
|
387
|
+
def _determinant_gauss(self):
|
|
388
|
+
"""Determinant by Gaussian elimination with partial pivoting."""
|
|
389
|
+
n = self.rows
|
|
390
|
+
a = [row[:] for row in self.m]
|
|
391
|
+
det = 1
|
|
392
|
+
for k in range(n):
|
|
393
|
+
pivot_row = max(range(k, n), key=lambda r: abs(a[r][k]))
|
|
394
|
+
if a[pivot_row][k] == 0:
|
|
395
|
+
# Whole column below is zero: the matrix is singular.
|
|
396
|
+
return det * 0
|
|
397
|
+
if pivot_row != k:
|
|
398
|
+
a[k], a[pivot_row] = a[pivot_row], a[k]
|
|
399
|
+
det = -det
|
|
400
|
+
pivot = a[k][k]
|
|
401
|
+
det = det * pivot
|
|
402
|
+
for i in range(k + 1, n):
|
|
403
|
+
factor = a[i][k] / pivot
|
|
404
|
+
if factor:
|
|
405
|
+
for j in range(k, n):
|
|
406
|
+
a[i][j] = a[i][j] - factor * a[k][j]
|
|
407
|
+
return det
|
|
408
|
+
|
|
409
|
+
# ``det()`` is the short form of determinant().
|
|
410
|
+
det = determinant
|
|
411
|
+
|
|
412
|
+
def inverse(self):
|
|
413
|
+
"""Return ``adjugate() / determinant()`` as a new Matrix.
|
|
414
|
+
|
|
415
|
+
Note: for an integer matrix this performs a true division, so the
|
|
416
|
+
entries of the result are floats.
|
|
417
|
+
"""
|
|
418
|
+
self._check_square("inverse")
|
|
419
|
+
det = self.determinant()
|
|
420
|
+
if det == 0:
|
|
421
|
+
raise ValueError("matrix is singular and cannot be inverted")
|
|
422
|
+
if isinstance(det, float) and abs(det) < 1e-12:
|
|
423
|
+
raise ValueError("matrix is numerically singular and cannot be inverted")
|
|
424
|
+
return self.adjugate() / det
|
|
425
|
+
|
|
426
|
+
# ``inv()`` is the short form of inverse().
|
|
427
|
+
inv = inverse
|
|
428
|
+
|
|
429
|
+
def trace(self):
|
|
430
|
+
"""Return the sum of the main diagonal."""
|
|
431
|
+
self._check_square("trace")
|
|
432
|
+
return sum(self.m[i][i] for i in range(self.rows))
|
|
433
|
+
|
|
434
|
+
@classmethod
|
|
435
|
+
def identity(cls, n: int):
|
|
436
|
+
"""Return the ``n x n`` identity matrix."""
|
|
437
|
+
return cls([[1 if i == j else 0 for j in range(n)] for i in range(n)])
|
|
438
|
+
|
|
439
|
+
# ``eye`` is the numpy-flavoured alias.
|
|
440
|
+
eye = identity
|
|
441
|
+
|
|
442
|
+
@classmethod
|
|
443
|
+
def zeros(cls, rows: int, cols: int):
|
|
444
|
+
"""Return a ``rows x cols`` matrix filled with zeros."""
|
|
445
|
+
return cls(dim=(rows, cols))
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def _selftest():
|
|
449
|
+
"""Exercise determinant / minor / cofactor / adjugate / inverse."""
|
|
450
|
+
def close(x, y, eps=1e-9):
|
|
451
|
+
return abs(x - y) <= eps
|
|
452
|
+
|
|
453
|
+
def assert_mat_close(a, b, eps=1e-9):
|
|
454
|
+
assert a.dim == b.dim, (a.dim, b.dim)
|
|
455
|
+
for i in range(a.rows):
|
|
456
|
+
for j in range(a.cols):
|
|
457
|
+
assert close(a[i, j], b[i, j]), (i, j, a[i, j], b[i, j])
|
|
458
|
+
|
|
459
|
+
print("--- self test ---")
|
|
460
|
+
|
|
461
|
+
# 1) determinant of a 2x2 and a 3x3 matrix
|
|
462
|
+
assert Matrix([[1, 2], [3, 4]]).determinant() == -2
|
|
463
|
+
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
|
|
464
|
+
print("A =", A)
|
|
465
|
+
print("det(A) =", A.determinant())
|
|
466
|
+
assert A.determinant() == -3
|
|
467
|
+
|
|
468
|
+
# 2) minor / cofactor
|
|
469
|
+
print("minor(0, 2) =", A.minor(0, 2))
|
|
470
|
+
print("cofactor(0, 2) =", A.cofactor(0, 2))
|
|
471
|
+
assert A.minor(0, 2) == Matrix([[4, 5], [7, 8]])
|
|
472
|
+
assert A.cofactor(0, 2) == -3
|
|
473
|
+
|
|
474
|
+
# 3) cofactor matrix / adjugate
|
|
475
|
+
print("cofactor_matrix(A) =", A.cofactor_matrix())
|
|
476
|
+
print("adjugate(A) =", A.adjugate())
|
|
477
|
+
assert A.cofactor_matrix().dim == (3, 3)
|
|
478
|
+
assert A.cofactor_matrix().T == A.adjugate()
|
|
479
|
+
# A @ adj(A) == det(A) * I
|
|
480
|
+
assert_mat_close(A @ A.adjugate(), A.determinant() * Matrix.identity(3))
|
|
481
|
+
|
|
482
|
+
# 4) inverse (integer entries, exact result here)
|
|
483
|
+
B = Matrix([[2, 1, 0], [1, 3, 1], [0, 1, 2]])
|
|
484
|
+
print("B =", B)
|
|
485
|
+
print("det(B) =", B.determinant())
|
|
486
|
+
print("inverse(B) =", B.inverse())
|
|
487
|
+
assert B.determinant() == 8
|
|
488
|
+
assert_mat_close(B @ B.inverse(), Matrix.identity(3))
|
|
489
|
+
assert_mat_close(B.inverse() @ B, Matrix.identity(3))
|
|
490
|
+
|
|
491
|
+
# 5) edge cases
|
|
492
|
+
assert Matrix([[4]]).inverse() == Matrix([[0.25]])
|
|
493
|
+
assert Matrix([[1, 2], [3, 4]]).inverse() == Matrix([[-2.0, 1.0], [1.5, -0.5]])
|
|
494
|
+
assert Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).determinant() == 0
|
|
495
|
+
assert Matrix([[1, 2, 3, 4],
|
|
496
|
+
[5, 6, 7, 8],
|
|
497
|
+
[9, 10, 11, 12],
|
|
498
|
+
[13, 14, 15, 16]]).determinant() == 0
|
|
499
|
+
try:
|
|
500
|
+
Matrix([[1, 2], [2, 4]]).inverse()
|
|
501
|
+
except ValueError as exc:
|
|
502
|
+
print("singular matrix:", exc)
|
|
503
|
+
else:
|
|
504
|
+
raise AssertionError("inverse() of a singular matrix must raise ValueError")
|
|
505
|
+
|
|
506
|
+
# 6) transpose (was broken before) and vector helpers
|
|
507
|
+
assert A.transpose().dim == (3, 3)
|
|
508
|
+
assert A.transpose()[0, 1] == A[1, 0]
|
|
509
|
+
assert A.T == A.transpose()
|
|
510
|
+
u = Vector([1, 2, 3], 3)
|
|
511
|
+
v = Vector([4, 5, 6], 3)
|
|
512
|
+
assert u + v == Vector([5, 7, 9], 3)
|
|
513
|
+
assert u.dot(v) == 32
|
|
514
|
+
assert u.modulus == 14 ** 0.5
|
|
515
|
+
|
|
516
|
+
print("all self tests passed")
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
if __name__ == '__main__':
|
|
520
|
+
print('packname: is_calc')
|
|
521
|
+
print('introduction: A tool includes some calculate function.')
|
|
522
|
+
_selftest()
|
|
523
|
+
print('is_calc end')
|