field.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """Implementation of :class:`Field` class. """
  2. from sympy.polys.domains.ring import Ring
  3. from sympy.polys.polyerrors import NotReversible, DomainError
  4. from sympy.utilities import public
  5. @public
  6. class Field(Ring):
  7. """Represents a field domain. """
  8. is_Field = True
  9. is_PID = True
  10. def get_ring(self):
  11. """Returns a ring associated with ``self``. """
  12. raise DomainError('there is no ring associated with %s' % self)
  13. def get_field(self):
  14. """Returns a field associated with ``self``. """
  15. return self
  16. def exquo(self, a, b):
  17. """Exact quotient of ``a`` and ``b``, implies ``__truediv__``. """
  18. return a / b
  19. def quo(self, a, b):
  20. """Quotient of ``a`` and ``b``, implies ``__truediv__``. """
  21. return a / b
  22. def rem(self, a, b):
  23. """Remainder of ``a`` and ``b``, implies nothing. """
  24. return self.zero
  25. def div(self, a, b):
  26. """Division of ``a`` and ``b``, implies ``__truediv__``. """
  27. return a / b, self.zero
  28. def gcd(self, a, b):
  29. """
  30. Returns GCD of ``a`` and ``b``.
  31. This definition of GCD over fields allows to clear denominators
  32. in `primitive()`.
  33. Examples
  34. ========
  35. >>> from sympy.polys.domains import QQ
  36. >>> from sympy import S, gcd, primitive
  37. >>> from sympy.abc import x
  38. >>> QQ.gcd(QQ(2, 3), QQ(4, 9))
  39. 2/9
  40. >>> gcd(S(2)/3, S(4)/9)
  41. 2/9
  42. >>> primitive(2*x/3 + S(4)/9)
  43. (2/9, 3*x + 2)
  44. """
  45. try:
  46. ring = self.get_ring()
  47. except DomainError:
  48. return self.one
  49. p = ring.gcd(self.numer(a), self.numer(b))
  50. q = ring.lcm(self.denom(a), self.denom(b))
  51. return self.convert(p, ring)/q
  52. def lcm(self, a, b):
  53. """
  54. Returns LCM of ``a`` and ``b``.
  55. >>> from sympy.polys.domains import QQ
  56. >>> from sympy import S, lcm
  57. >>> QQ.lcm(QQ(2, 3), QQ(4, 9))
  58. 4/3
  59. >>> lcm(S(2)/3, S(4)/9)
  60. 4/3
  61. """
  62. try:
  63. ring = self.get_ring()
  64. except DomainError:
  65. return a*b
  66. p = ring.lcm(self.numer(a), self.numer(b))
  67. q = ring.gcd(self.denom(a), self.denom(b))
  68. return self.convert(p, ring)/q
  69. def revert(self, a):
  70. """Returns ``a**(-1)`` if possible. """
  71. if a:
  72. return 1/a
  73. else:
  74. raise NotReversible('zero is not reversible')
  75. def is_unit(self, a):
  76. """Return true if ``a`` is a invertible"""
  77. return bool(a)