diff --git a/CHANGELOG.md b/CHANGELOG.md index afce9e69104..acc07f5a49b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * Changed use of `compas.geometry.allclose` to `compas.tolerance.TOL.is_allclose`. * Changed use of `compas.geometry.close` to `compas.tolerance.TOL.is_close`. * Changed imports of itertools to `compas.itertools` instead of `compas.utilities`. +* Updated `compas.geometry.vector` with `__rmul__` and allow element-wise multiplication and division with another vector. ### Removed diff --git a/src/compas/geometry/vector.py b/src/compas/geometry/vector.py index 8e1b5702257..3f440752265 100644 --- a/src/compas/geometry/vector.py +++ b/src/compas/geometry/vector.py @@ -148,11 +148,21 @@ def __add__(self, other): def __sub__(self, other): return Vector(self.x - other[0], self.y - other[1], self.z - other[2]) - def __mul__(self, n): - return Vector(self.x * n, self.y * n, self.z * n) - - def __truediv__(self, n): - return Vector(self.x / n, self.y / n, self.z / n) + def __mul__(self, other): + if isinstance(other, (int, float)): + return Vector(self.x * other, self.y * other, self.z * other) + elif isinstance(other, Vector): + return Vector(self.x * other[0], self.y * other[1], self.z * other[2]) + else: + raise TypeError("Multiplication of Vector with unsupported type: {}".format(type(other))) + + def __truediv__(self, other): + if isinstance(other, (int, float)): + return Vector(self.x / other, self.y / other, self.z / other) + elif isinstance(other, Vector): + return Vector(self.x / other[0], self.y / other[1], self.z / other[2]) + else: + raise TypeError("Division of Vector with unsupported type: {}".format(type(other))) def __pow__(self, n): return Vector(self.x**n, self.y**n, self.z**n) @@ -190,6 +200,9 @@ def __ipow__(self, n): self.z **= n return self + def __rmul__(self, n): + return self.__mul__(n) + # ========================================================================== # Properties # ========================================================================== diff --git a/tests/compas/geometry/test_vector.py b/tests/compas/geometry/test_vector.py index ba76c1e42ee..647531a2495 100644 --- a/tests/compas/geometry/test_vector.py +++ b/tests/compas/geometry/test_vector.py @@ -52,6 +52,10 @@ def test_vector_operators(): assert a * 2 == [a.x * 2, a.y * 2, a.z * 2] assert a / 2 == [a.x / 2, a.y / 2, a.z / 2] assert a**3 == [a.x**3, a.y**3, a.z**3] + assert 2 * a == [2 * a.x, 2 * a.y, 2 * a.z] + assert a * b == [a.x * b.x, a.y * b.y, a.z * b.z] + assert b * a == [a.x * b.x, a.y * b.y, a.z * b.z] + assert a / b == [a.x / b.x, a.y / b.y, a.z / b.z] def test_vector_equality():