Skip to content

Commit

Permalink
feat: Vector addition
Browse files Browse the repository at this point in the history
  • Loading branch information
unexcellent committed Nov 13, 2024
1 parent 0721e9b commit 23caa76
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
12 changes: 12 additions & 0 deletions quantio/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,15 @@ def __getitem__(self, index: int) -> T:
def __setitem__(self, index: int, value: T) -> None:
"""Set the element at a specific index."""
self._elements[index] = value

def __add__(self, other: Vector[T] | np.ndarray) -> Vector[T]:
"""Add another vector to this one."""
other_elements = other._elements if isinstance(other, Vector) else np.array(other)
return Vector[T](self._elements + other_elements)

def __eq__(self, other: object) -> bool:
"""Assess if this object is the same as another."""
if not isinstance(other, Vector):
return False

return np.all(other._elements == self._elements)
18 changes: 17 additions & 1 deletion test/test_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import numpy as np

from quantio import Vector, Length
from quantio import Vector, Length, CanNotAddTypesError


def test_init():
Expand All @@ -27,5 +27,21 @@ def test_set_item():
assert vec[0] == Length(meters=3)


def test_addition():
vec1: Vector[Length] = Vector([Length(meters=1), Length(meters=2)])
vec2: Vector[Length] = Vector([Length(meters=3), Length(meters=4)])

actual = vec1 + vec2
assert actual == Vector([Length(meters=4), Length(meters=6)])


def test_addition__wrong_type():
vec1: Vector[Length] = Vector([Length(meters=1), Length(meters=2)])
vec2: Vector[float] = Vector([3, 4])

with pytest.raises(CanNotAddTypesError):
vec1 + vec2


if __name__ == "__main__":
pytest.main([__file__, "-v"])

0 comments on commit 23caa76

Please sign in to comment.