Coverage for /usr/lib/python3/dist-packages/sympy/polys/domains/pythonrationalfield.py: 52%
40 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
1"""Implementation of :class:`PythonRationalField` class. """
4from sympy.polys.domains.groundtypes import PythonInteger, PythonRational, SymPyRational
5from sympy.polys.domains.rationalfield import RationalField
6from sympy.polys.polyerrors import CoercionFailed
7from sympy.utilities import public
9@public
10class PythonRationalField(RationalField):
11 """Rational field based on :ref:`MPQ`.
13 This will be used as :ref:`QQ` if ``gmpy`` and ``gmpy2`` are not
14 installed. Elements are instances of :ref:`MPQ`.
15 """
17 dtype = PythonRational
18 zero = dtype(0)
19 one = dtype(1)
20 alias = 'QQ_python'
22 def __init__(self):
23 pass
25 def get_ring(self):
26 """Returns ring associated with ``self``. """
27 from sympy.polys.domains import PythonIntegerRing
28 return PythonIntegerRing()
30 def to_sympy(self, a):
31 """Convert `a` to a SymPy object. """
32 return SymPyRational(a.numerator, a.denominator)
34 def from_sympy(self, a):
35 """Convert SymPy's Rational to `dtype`. """
36 if a.is_Rational:
37 return PythonRational(a.p, a.q)
38 elif a.is_Float:
39 from sympy.polys.domains import RR
40 p, q = RR.to_rational(a)
41 return PythonRational(int(p), int(q))
42 else:
43 raise CoercionFailed("expected `Rational` object, got %s" % a)
45 def from_ZZ_python(K1, a, K0):
46 """Convert a Python `int` object to `dtype`. """
47 return PythonRational(a)
49 def from_QQ_python(K1, a, K0):
50 """Convert a Python `Fraction` object to `dtype`. """
51 return a
53 def from_ZZ_gmpy(K1, a, K0):
54 """Convert a GMPY `mpz` object to `dtype`. """
55 return PythonRational(PythonInteger(a))
57 def from_QQ_gmpy(K1, a, K0):
58 """Convert a GMPY `mpq` object to `dtype`. """
59 return PythonRational(PythonInteger(a.numer()),
60 PythonInteger(a.denom()))
62 def from_RealField(K1, a, K0):
63 """Convert a mpmath `mpf` object to `dtype`. """
64 p, q = K0.to_rational(a)
65 return PythonRational(int(p), int(q))
67 def numer(self, a):
68 """Returns numerator of `a`. """
69 return a.numerator
71 def denom(self, a):
72 """Returns denominator of `a`. """
73 return a.denominator