Skip to content

Commit

Permalink
fix: enforce simple form uniqueness of element sequences in `Continue…
Browse files Browse the repository at this point in the history
…dFraction.extend` op + update tests
  • Loading branch information
sr-murthy committed Oct 26, 2024
1 parent 078c9bf commit c3854a2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/continuedfractions/continuedfraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,17 @@ def extend(self, *new_elements: int) -> None:
)

elements = self._elements + new_elements

# A step to ensure uniqueness of the simple form of the continued
# fraction - if the last of the new elements is ``1`` it can be
# "absorbed" by adding it to the second last element, thereby
# shortening the sequence by one element. The resulting simple
# continued fraction becomes unique for the number that is represented.
if len(elements) > 1 and elements[-1] == 1:
elements = elements[:-2] + (elements[-2] + 1,)

fraction = fraction_from_elements(*elements)

self._numerator, self._denominator = fraction.as_integer_ratio()
self._elements = elements

Expand Down
5 changes: 5 additions & 0 deletions tests/units/test_continuedfraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,8 +561,13 @@ def test_ContinuedFraction__extend__invalid_elements__value_error_raised(self, i
@pytest.mark.parametrize(
"instance, new_elements, expected_comparative_instance",
[
(ContinuedFraction(0, 1), (1,), ContinuedFraction(1, 1)),
(ContinuedFraction(0, 1), (2,), ContinuedFraction(1, 2)),
(ContinuedFraction(0, 1), (2, 1,), ContinuedFraction(1, 3)),
(ContinuedFraction(0, 1), (3,), ContinuedFraction(1, 3)),
(ContinuedFraction(1, 1), (2,), ContinuedFraction(3, 2)),
(ContinuedFraction(1, 1), (2, 1), ContinuedFraction(4, 3)),
(ContinuedFraction(1, 1), (3,), ContinuedFraction(4, 3)),
(ContinuedFraction(3, 2), (3,), ContinuedFraction(10, 7)),
(ContinuedFraction(649, 200), (5, 2), ContinuedFraction(7457, 2298)),
(ContinuedFraction(-415, 93), (2, 1, 5), ContinuedFraction(-7403, 1659))
Expand Down

0 comments on commit c3854a2

Please sign in to comment.