Skip to content

Commit

Permalink
Vector multiplications
Browse files Browse the repository at this point in the history
  • Loading branch information
Licini committed Apr 29, 2024
1 parent c2516e9 commit c7f958c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
23 changes: 18 additions & 5 deletions src/compas/geometry/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -190,6 +200,9 @@ def __ipow__(self, n):
self.z **= n
return self

def __rmul__(self, n):
return self.__mul__(n)

# ==========================================================================
# Properties
# ==========================================================================
Expand Down
4 changes: 4 additions & 0 deletions tests/compas/geometry/test_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down

0 comments on commit c7f958c

Please sign in to comment.