Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import math
- import numpy as np
- from typing import Any, Iterable
- def matrix_to_geolin_answer(
- matrix: Iterable[Iterable[Any]], digits: int = 2, eps: float = 1e-5
- ) -> str:
- ans = "; ".join(
- [
- ", ".join(
- (str(round(e)) if (abs(round(e) - e) < eps) else str(round(e, digits)))
- for e in row
- )
- for row in matrix
- ]
- )
- return "[" + ans + "]"
- def gram_multiply(x: np.ndarray, y: np.ndarray, gram: np.ndarray) -> int:
- return np.dot(np.dot(np.transpose(x), gram), y).astype(np.int64)
- def ortogonalize(vectors: np.ndarray, gram: np.ndarray | None = None) -> np.ndarray:
- vectors = vectors.astype(np.int64)
- n = vectors.shape[1]
- if gram is None:
- gram = np.identity(n)
- gram = gram.astype(np.int64)
- ans: list[np.ndarray] = []
- for f in vectors:
- r = f
- m = 1
- for g in ans:
- nom = gram_multiply(f, g, gram)
- denom = gram_multiply(g, g, gram)
- m = math.lcm(m, denom // math.gcd(nom, denom))
- r = np.subtract(r, np.dot(nom / denom, g))
- ans.append(np.round(r * m).astype(np.int64))
- return np.array(ans)
- vectors = np.array([[1, -1, -1, 2, 3], [-1, 2, 2, -6, -5], [1, -1, -2, 3, 5]])
- gram = np.array(
- [
- [4, -2, 2, -2, 2],
- [-2, 12, -2, -2, -2],
- [2, -2, 4, -6, 2],
- [-2, -2, -6, 12, -2],
- [2, -2, 2, -2, 2],
- ]
- )
- ans = ortogonalize(vectors, gram)
- print(ans)
- print(matrix_to_geolin_answer(ans))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement