pythonrationalfield.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """Implementation of :class:`PythonRationalField` class. """
  2. from sympy.polys.domains.groundtypes import PythonInteger, PythonRational, SymPyRational
  3. from sympy.polys.domains.rationalfield import RationalField
  4. from sympy.polys.polyerrors import CoercionFailed
  5. from sympy.utilities import public
  6. @public
  7. class PythonRationalField(RationalField):
  8. """Rational field based on :ref:`MPQ`.
  9. This will be used as :ref:`QQ` if ``gmpy`` and ``gmpy2`` are not
  10. installed. Elements are instances of :ref:`MPQ`.
  11. """
  12. dtype = PythonRational
  13. zero = dtype(0)
  14. one = dtype(1)
  15. alias = 'QQ_python'
  16. def __init__(self):
  17. pass
  18. def get_ring(self):
  19. """Returns ring associated with ``self``. """
  20. from sympy.polys.domains import PythonIntegerRing
  21. return PythonIntegerRing()
  22. def to_sympy(self, a):
  23. """Convert `a` to a SymPy object. """
  24. return SymPyRational(a.numerator, a.denominator)
  25. def from_sympy(self, a):
  26. """Convert SymPy's Rational to `dtype`. """
  27. if a.is_Rational:
  28. return PythonRational(a.p, a.q)
  29. elif a.is_Float:
  30. from sympy.polys.domains import RR
  31. p, q = RR.to_rational(a)
  32. return PythonRational(int(p), int(q))
  33. else:
  34. raise CoercionFailed("expected `Rational` object, got %s" % a)
  35. def from_ZZ_python(K1, a, K0):
  36. """Convert a Python `int` object to `dtype`. """
  37. return PythonRational(a)
  38. def from_QQ_python(K1, a, K0):
  39. """Convert a Python `Fraction` object to `dtype`. """
  40. return a
  41. def from_ZZ_gmpy(K1, a, K0):
  42. """Convert a GMPY `mpz` object to `dtype`. """
  43. return PythonRational(PythonInteger(a))
  44. def from_QQ_gmpy(K1, a, K0):
  45. """Convert a GMPY `mpq` object to `dtype`. """
  46. return PythonRational(PythonInteger(a.numer()),
  47. PythonInteger(a.denom()))
  48. def from_RealField(K1, a, K0):
  49. """Convert a mpmath `mpf` object to `dtype`. """
  50. p, q = K0.to_rational(a)
  51. return PythonRational(int(p), int(q))
  52. def numer(self, a):
  53. """Returns numerator of `a`. """
  54. return a.numerator
  55. def denom(self, a):
  56. """Returns denominator of `a`. """
  57. return a.denominator