Skip to content

Commit

Permalink
Merge pull request #443 from qutech/issues/442_time_type
Browse files Browse the repository at this point in the history
Add an explicit creation of the time type from nominator and denominator

Closes #442
  • Loading branch information
terrorfisch authored Mar 25, 2019
2 parents 3d6eaa6 + a611a74 commit 499b62f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
7 changes: 7 additions & 0 deletions qupulse/utils/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
def time_from_float(time: float, absolute_error: float=1e-12) -> TimeType:
# gmpy2 is at least an order of magnitude faster than fractions.Fraction
return gmpy2.mpq(gmpy2.f2q(time, absolute_error))

def time_from_fraction(numerator: int, denominator: int = 1) -> TimeType:
return gmpy2.mpq(numerator, denominator)

except ImportError:
warnings.warn('gmpy2 not found. Using fractions.Fraction as fallback. Install gmpy2 for better performance.')

Expand All @@ -29,6 +33,9 @@ def time_from_float(time: float, absolute_error: float=1e-12) -> TimeType:
def time_from_float(time: float, absolute_error: float = 1e-12) -> TimeType:
return fractions.Fraction(time).limit_denominator(int(1/absolute_error))

def time_from_fraction(numerator: int, denominator: int = 1) -> TimeType:
return fractions.Fraction(numerator=numerator, denominator=denominator)


class DocStringABCMeta(abc.ABCMeta):
"""Metaclass that copies/refers to docstrings of the super class."""
Expand Down
15 changes: 15 additions & 0 deletions tests/utils/time_type_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,18 @@ def test_fraction_time_from_float(self):
self.assertEqual(self.fallback_qutypes.time_from_float(1000000 / 1000001, 1e-5),
fractions.Fraction(1))

@unittest.skipIf(gmpy2 is None, "gmpy2 not available.")
def test_default_time_from_fraction(self):
# assert mocking did no permanent damage
self.assertIs(gmpy2.mpq, qutypes.TimeType)

t = qutypes.time_from_fraction(43, 12)
# your challenge: find a better way
mpq_type = type(gmpy2.mpq())
self.assertIsInstance(t, mpq_type)
self.assertEqual(t, gmpy2.mpq(43, 12))

def test_fraction_time_from_fraction(self):
t = qutypes.time_from_fraction(43, 12)
self.assertIsInstance(t, fractions.Fraction)
self.assertEqual(t, fractions.Fraction(43, 12))

0 comments on commit 499b62f

Please sign in to comment.