MoonGame/compute.py
2025-10-30 20:05:43 +01:00

44 lines
1.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import List, Tuple
import math
Matrix = List[List[float]]
Vector = Tuple[float, float]
def transpose(m: Matrix) -> Matrix:
if not m or not m[0]:
raise ValueError("Matrix must be non-empty")
return [list(row) for row in zip(*m)]
def matmul(a: Matrix, b: Matrix) -> Matrix: #Matrixmultiplikation#
if not a or not b or not a[0] or not b[0]:
raise ValueError("Matrices must be non-empty")
m, n = len(a), len(a[0])
n2, p = len(b), len(b[0])
if n != n2:
raise ValueError("Incompatible shapes")
c: Matrix = [[0.0 for _ in range(p)] for _ in range(m)]
for i in range(m):
for k in range(n):
a_ik = float(a[i][k])
for j in range(p):
c[i][j] += a_ik * float(b[k][j])
def rotation_matrix(theta: float) -> Matrix:
"""2D-Rotationsmatrix R(theta)."""
c, s = math.cos(theta), math.sin(theta)
return [[c, -s],
[s, c]]
def apply_mat_to_vec(m: Matrix, v: Vector) -> Vector:
"""Wendet eine 2×2-Matrix auf einen 2D-Vektor (als Spaltenvektor) an."""
if len(m) != 2 or len(m[0]) != 2:
raise ValueError("Matrix must be 2x2 for 2D vector transform")
x, y = float(v[0]), float(v[1])
x2 = m[0][0]*x + m[0][1]*y
y2 = m[1][0]*x + m[1][1]*y
return (x2, y2)
def add(v1: Vector, v2: Vector) -> Vector:
"""Vektor-Addition v1 + v2."""
return (v1[0] + v2[0], v1[1] + v2[1])