Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add tests for Vector2.isclose #96

Merged
merged 5 commits into from
Dec 31, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions ppb_vector/vector2.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,9 @@ def isclose(self: VectorOrSub, other: VectorLike, *,
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
"""
if abs_tol < 0 or rel_tol < 0:
raise ValueError("Vector2.isclose takes non-negative tolerances")

other = Vector2.convert(other)

rel_length = max(
Expand All @@ -241,8 +244,8 @@ def isclose(self: VectorOrSub, other: VectorLike, *,

diff = (self - other).length
return (
diff < rel_tol * rel_length or
diff < float(abs_tol)
diff <= rel_tol * rel_length or
diff <= float(abs_tol)
)

@staticmethod
Expand Down
30 changes: 30 additions & 0 deletions tests/test_vector2_isclose.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from ppb_vector import Vector2
from pytest import raises # type: ignore
from utils import units, vectors
from hypothesis import assume, given, note, example
from hypothesis.strategies import floats


@given(x=vectors(), abs_tol=floats(min_value=0), rel_tol=floats(min_value=0))
def test_isclose_to_self(x, abs_tol, rel_tol):
assert x.isclose(x, abs_tol=abs_tol, rel_tol=rel_tol)

@given(x=vectors(max_magnitude=1e75), direction=units(),
abs_tol=floats(min_value=0, max_value=1e75))
def test_isclose_abs_error(x, direction, abs_tol):
assert x.isclose(x + (1 - 1e-12) * abs_tol * direction, abs_tol=abs_tol, rel_tol=0)

@given(x=vectors(), direction=units(),
rel_tol=floats(min_value=0, max_value=1e75))
def test_isclose_rel_error(x, direction, rel_tol):
assert x.isclose(x + rel_tol * x.length * direction, abs_tol=0, rel_tol=rel_tol)


def test_isclose_negative_tolerances():
zero = Vector2(0, 0)

with raises(ValueError):
zero.isclose(zero, abs_tol=-1)

with raises(ValueError):
zero.isclose(zero, rel_tol=-1)