92 lines
2.5 KiB
Python
92 lines
2.5 KiB
Python
# %%
|
|
# Ausdrücke berechnen
|
|
import numpy as np
|
|
|
|
|
|
# Vector Klasse um fehler abzufangen wie Vektor + Skalar. Numpy führt das aus, ist aber mathematisch nicht definiert.
|
|
class Vector:
|
|
def __init__(self, values):
|
|
self._values = np.asarray(values)
|
|
|
|
def __add__(self, other):
|
|
if not isinstance(other, Vector):
|
|
raise TypeError("Can only add vectors")
|
|
if self._values.shape != other._values.shape:
|
|
raise ValueError("Vectors must have the same dimension")
|
|
return Vector(self._values + other._values)
|
|
|
|
def __sub__(self, other):
|
|
if not isinstance(other, Vector):
|
|
raise TypeError("Can only subtract vectors")
|
|
return Vector(self._values - other._values)
|
|
|
|
def __mul__(self, other):
|
|
if isinstance(other, Vector):
|
|
# Vector * Vector = dot product
|
|
return np.dot(self._values, other._values)
|
|
|
|
if np.isscalar(other):
|
|
# Vector * scalar = scaled vector
|
|
return Vector(self._values * other)
|
|
|
|
return NotImplemented
|
|
|
|
def __rmul__(self, scalar):
|
|
return self * scalar
|
|
|
|
def cross(self, other):
|
|
if not isinstance(other, Vector):
|
|
raise TypeError("Cross product requires two vectors")
|
|
return Vector(np.cross(self._values, other._values))
|
|
|
|
def __abs__(self):
|
|
return np.linalg.norm(self._values)
|
|
|
|
def __repr__(self):
|
|
return f"Vector({self._values})"
|
|
|
|
|
|
a = Vector([3.8, 2.12, -4.01])
|
|
b = Vector([0.01, -0.02, 2.341])
|
|
c = Vector([-5.1, 1.0, 4.5])
|
|
d = Vector([1.0, 0.32])
|
|
|
|
|
|
operations = [
|
|
lambda: 4 * a + 2.1 * (b * c),
|
|
lambda: -8.35 * a.cross(c) * b - abs(d) ** 2,
|
|
lambda: (3.1 * d).cross(a) - (a * 2 * c) * b,
|
|
lambda: a * (1 / abs(d)) - (2 * b - 9.33 * c),
|
|
]
|
|
|
|
for operation in operations:
|
|
try:
|
|
print(operation())
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
|
|
#%%
|
|
import numpy as np
|
|
|
|
a = np.array([3.8, 2.12, -4.01])
|
|
b = np.array([0.01, -0.02, 2.341])
|
|
c = np.array([-5.1, 1.0, 4.5])
|
|
d = np.array([1.0, 0.32])
|
|
|
|
# 4 * a + 2.1 * (b @ c) is mathematically not defined, but numpy will run it anyways, becaus it fills array fiels with 0. Native numpy can't catch this error
|
|
operations = [
|
|
lambda: 4 * a + 2.1 * (b @ c),
|
|
lambda: -8.35 * np.cross(a, c) @ b - np.linalg.norm(d) ** 2,
|
|
lambda: np.cross(3.1 * d, a) - (a @ (2 * c)) * b,
|
|
lambda: a * (1 / np.linalg.norm(d)) - (2 * b - 9.33 * c),
|
|
]
|
|
|
|
for operation in operations:
|
|
try:
|
|
print(operation())
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
|
|
|
|
# %%
|