numbers.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. # Copyright 2007 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Abstract Base Classes (ABCs) for numbers, according to PEP 3141.
  4. TODO: Fill out more detailed documentation on the operators."""
  5. from abc import ABCMeta, abstractmethod
  6. __all__ = ["Number", "Complex", "Real", "Rational", "Integral"]
  7. class Number(metaclass=ABCMeta):
  8. """All numbers inherit from this class.
  9. If you just want to check if an argument x is a number, without
  10. caring what kind, use isinstance(x, Number).
  11. """
  12. __slots__ = ()
  13. # Concrete numeric types must provide their own hash implementation
  14. __hash__ = None
  15. ## Notes on Decimal
  16. ## ----------------
  17. ## Decimal has all of the methods specified by the Real abc, but it should
  18. ## not be registered as a Real because decimals do not interoperate with
  19. ## binary floats (i.e. Decimal('3.14') + 2.71828 is undefined). But,
  20. ## abstract reals are expected to interoperate (i.e. R1 + R2 should be
  21. ## expected to work if R1 and R2 are both Reals).
  22. class Complex(Number):
  23. """Complex defines the operations that work on the builtin complex type.
  24. In short, those are: a conversion to complex, .real, .imag, +, -,
  25. *, /, **, abs(), .conjugate, ==, and !=.
  26. If it is given heterogeneous arguments, and doesn't have special
  27. knowledge about them, it should fall back to the builtin complex
  28. type as described below.
  29. """
  30. __slots__ = ()
  31. @abstractmethod
  32. def __complex__(self):
  33. """Return a builtin complex instance. Called for complex(self)."""
  34. def __bool__(self):
  35. """True if self != 0. Called for bool(self)."""
  36. return self != 0
  37. @property
  38. @abstractmethod
  39. def real(self):
  40. """Retrieve the real component of this number.
  41. This should subclass Real.
  42. """
  43. raise NotImplementedError
  44. @property
  45. @abstractmethod
  46. def imag(self):
  47. """Retrieve the imaginary component of this number.
  48. This should subclass Real.
  49. """
  50. raise NotImplementedError
  51. @abstractmethod
  52. def __add__(self, other):
  53. """self + other"""
  54. raise NotImplementedError
  55. @abstractmethod
  56. def __radd__(self, other):
  57. """other + self"""
  58. raise NotImplementedError
  59. @abstractmethod
  60. def __neg__(self):
  61. """-self"""
  62. raise NotImplementedError
  63. @abstractmethod
  64. def __pos__(self):
  65. """+self"""
  66. raise NotImplementedError
  67. def __sub__(self, other):
  68. """self - other"""
  69. return self + -other
  70. def __rsub__(self, other):
  71. """other - self"""
  72. return -self + other
  73. @abstractmethod
  74. def __mul__(self, other):
  75. """self * other"""
  76. raise NotImplementedError
  77. @abstractmethod
  78. def __rmul__(self, other):
  79. """other * self"""
  80. raise NotImplementedError
  81. @abstractmethod
  82. def __truediv__(self, other):
  83. """self / other: Should promote to float when necessary."""
  84. raise NotImplementedError
  85. @abstractmethod
  86. def __rtruediv__(self, other):
  87. """other / self"""
  88. raise NotImplementedError
  89. @abstractmethod
  90. def __pow__(self, exponent):
  91. """self**exponent; should promote to float or complex when necessary."""
  92. raise NotImplementedError
  93. @abstractmethod
  94. def __rpow__(self, base):
  95. """base ** self"""
  96. raise NotImplementedError
  97. @abstractmethod
  98. def __abs__(self):
  99. """Returns the Real distance from 0. Called for abs(self)."""
  100. raise NotImplementedError
  101. @abstractmethod
  102. def conjugate(self):
  103. """(x+y*i).conjugate() returns (x-y*i)."""
  104. raise NotImplementedError
  105. @abstractmethod
  106. def __eq__(self, other):
  107. """self == other"""
  108. raise NotImplementedError
  109. Complex.register(complex)
  110. class Real(Complex):
  111. """To Complex, Real adds the operations that work on real numbers.
  112. In short, those are: a conversion to float, trunc(), divmod,
  113. %, <, <=, >, and >=.
  114. Real also provides defaults for the derived operations.
  115. """
  116. __slots__ = ()
  117. @abstractmethod
  118. def __float__(self):
  119. """Any Real can be converted to a native float object.
  120. Called for float(self)."""
  121. raise NotImplementedError
  122. @abstractmethod
  123. def __trunc__(self):
  124. """trunc(self): Truncates self to an Integral.
  125. Returns an Integral i such that:
  126. * i>0 iff self>0;
  127. * abs(i) <= abs(self);
  128. * for any Integral j satisfying the first two conditions,
  129. abs(i) >= abs(j) [i.e. i has "maximal" abs among those].
  130. i.e. "truncate towards 0".
  131. """
  132. raise NotImplementedError
  133. @abstractmethod
  134. def __floor__(self):
  135. """Finds the greatest Integral <= self."""
  136. raise NotImplementedError
  137. @abstractmethod
  138. def __ceil__(self):
  139. """Finds the least Integral >= self."""
  140. raise NotImplementedError
  141. @abstractmethod
  142. def __round__(self, ndigits=None):
  143. """Rounds self to ndigits decimal places, defaulting to 0.
  144. If ndigits is omitted or None, returns an Integral, otherwise
  145. returns a Real. Rounds half toward even.
  146. """
  147. raise NotImplementedError
  148. def __divmod__(self, other):
  149. """divmod(self, other): The pair (self // other, self % other).
  150. Sometimes this can be computed faster than the pair of
  151. operations.
  152. """
  153. return (self // other, self % other)
  154. def __rdivmod__(self, other):
  155. """divmod(other, self): The pair (self // other, self % other).
  156. Sometimes this can be computed faster than the pair of
  157. operations.
  158. """
  159. return (other // self, other % self)
  160. @abstractmethod
  161. def __floordiv__(self, other):
  162. """self // other: The floor() of self/other."""
  163. raise NotImplementedError
  164. @abstractmethod
  165. def __rfloordiv__(self, other):
  166. """other // self: The floor() of other/self."""
  167. raise NotImplementedError
  168. @abstractmethod
  169. def __mod__(self, other):
  170. """self % other"""
  171. raise NotImplementedError
  172. @abstractmethod
  173. def __rmod__(self, other):
  174. """other % self"""
  175. raise NotImplementedError
  176. @abstractmethod
  177. def __lt__(self, other):
  178. """self < other
  179. < on Reals defines a total ordering, except perhaps for NaN."""
  180. raise NotImplementedError
  181. @abstractmethod
  182. def __le__(self, other):
  183. """self <= other"""
  184. raise NotImplementedError
  185. # Concrete implementations of Complex abstract methods.
  186. def __complex__(self):
  187. """complex(self) == complex(float(self), 0)"""
  188. return complex(float(self))
  189. @property
  190. def real(self):
  191. """Real numbers are their real component."""
  192. return +self
  193. @property
  194. def imag(self):
  195. """Real numbers have no imaginary component."""
  196. return 0
  197. def conjugate(self):
  198. """Conjugate is a no-op for Reals."""
  199. return +self
  200. Real.register(float)
  201. class Rational(Real):
  202. """.numerator and .denominator should be in lowest terms."""
  203. __slots__ = ()
  204. @property
  205. @abstractmethod
  206. def numerator(self):
  207. raise NotImplementedError
  208. @property
  209. @abstractmethod
  210. def denominator(self):
  211. raise NotImplementedError
  212. # Concrete implementation of Real's conversion to float.
  213. def __float__(self):
  214. """float(self) = self.numerator / self.denominator
  215. It's important that this conversion use the integer's "true"
  216. division rather than casting one side to float before dividing
  217. so that ratios of huge integers convert without overflowing.
  218. """
  219. return self.numerator / self.denominator
  220. class Integral(Rational):
  221. """Integral adds methods that work on integral numbers.
  222. In short, these are conversion to int, pow with modulus, and the
  223. bit-string operations.
  224. """
  225. __slots__ = ()
  226. @abstractmethod
  227. def __int__(self):
  228. """int(self)"""
  229. raise NotImplementedError
  230. def __index__(self):
  231. """Called whenever an index is needed, such as in slicing"""
  232. return int(self)
  233. @abstractmethod
  234. def __pow__(self, exponent, modulus=None):
  235. """self ** exponent % modulus, but maybe faster.
  236. Accept the modulus argument if you want to support the
  237. 3-argument version of pow(). Raise a TypeError if exponent < 0
  238. or any argument isn't Integral. Otherwise, just implement the
  239. 2-argument version described in Complex.
  240. """
  241. raise NotImplementedError
  242. @abstractmethod
  243. def __lshift__(self, other):
  244. """self << other"""
  245. raise NotImplementedError
  246. @abstractmethod
  247. def __rlshift__(self, other):
  248. """other << self"""
  249. raise NotImplementedError
  250. @abstractmethod
  251. def __rshift__(self, other):
  252. """self >> other"""
  253. raise NotImplementedError
  254. @abstractmethod
  255. def __rrshift__(self, other):
  256. """other >> self"""
  257. raise NotImplementedError
  258. @abstractmethod
  259. def __and__(self, other):
  260. """self & other"""
  261. raise NotImplementedError
  262. @abstractmethod
  263. def __rand__(self, other):
  264. """other & self"""
  265. raise NotImplementedError
  266. @abstractmethod
  267. def __xor__(self, other):
  268. """self ^ other"""
  269. raise NotImplementedError
  270. @abstractmethod
  271. def __rxor__(self, other):
  272. """other ^ self"""
  273. raise NotImplementedError
  274. @abstractmethod
  275. def __or__(self, other):
  276. """self | other"""
  277. raise NotImplementedError
  278. @abstractmethod
  279. def __ror__(self, other):
  280. """other | self"""
  281. raise NotImplementedError
  282. @abstractmethod
  283. def __invert__(self):
  284. """~self"""
  285. raise NotImplementedError
  286. # Concrete implementations of Rational and Real abstract methods.
  287. def __float__(self):
  288. """float(self) == float(int(self))"""
  289. return float(int(self))
  290. @property
  291. def numerator(self):
  292. """Integers are their own numerators."""
  293. return +self
  294. @property
  295. def denominator(self):
  296. """Integers have a denominator of 1."""
  297. return 1
  298. Integral.register(int)