interval_arithmetic.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. """
  2. Interval Arithmetic for plotting.
  3. This module does not implement interval arithmetic accurately and
  4. hence cannot be used for purposes other than plotting. If you want
  5. to use interval arithmetic, use mpmath's interval arithmetic.
  6. The module implements interval arithmetic using numpy and
  7. python floating points. The rounding up and down is not handled
  8. and hence this is not an accurate implementation of interval
  9. arithmetic.
  10. The module uses numpy for speed which cannot be achieved with mpmath.
  11. """
  12. # Q: Why use numpy? Why not simply use mpmath's interval arithmetic?
  13. # A: mpmath's interval arithmetic simulates a floating point unit
  14. # and hence is slow, while numpy evaluations are orders of magnitude
  15. # faster.
  16. # Q: Why create a separate class for intervals? Why not use SymPy's
  17. # Interval Sets?
  18. # A: The functionalities that will be required for plotting is quite
  19. # different from what Interval Sets implement.
  20. # Q: Why is rounding up and down according to IEEE754 not handled?
  21. # A: It is not possible to do it in both numpy and python. An external
  22. # library has to used, which defeats the whole purpose i.e., speed. Also
  23. # rounding is handled for very few functions in those libraries.
  24. # Q Will my plots be affected?
  25. # A It will not affect most of the plots. The interval arithmetic
  26. # module based suffers the same problems as that of floating point
  27. # arithmetic.
  28. from sympy.core.logic import fuzzy_and
  29. from sympy.simplify.simplify import nsimplify
  30. from .interval_membership import intervalMembership
  31. class interval:
  32. """ Represents an interval containing floating points as start and
  33. end of the interval
  34. The is_valid variable tracks whether the interval obtained as the
  35. result of the function is in the domain and is continuous.
  36. - True: Represents the interval result of a function is continuous and
  37. in the domain of the function.
  38. - False: The interval argument of the function was not in the domain of
  39. the function, hence the is_valid of the result interval is False
  40. - None: The function was not continuous over the interval or
  41. the function's argument interval is partly in the domain of the
  42. function
  43. A comparison between an interval and a real number, or a
  44. comparison between two intervals may return ``intervalMembership``
  45. of two 3-valued logic values.
  46. """
  47. def __init__(self, *args, is_valid=True, **kwargs):
  48. self.is_valid = is_valid
  49. if len(args) == 1:
  50. if isinstance(args[0], interval):
  51. self.start, self.end = args[0].start, args[0].end
  52. else:
  53. self.start = float(args[0])
  54. self.end = float(args[0])
  55. elif len(args) == 2:
  56. if args[0] < args[1]:
  57. self.start = float(args[0])
  58. self.end = float(args[1])
  59. else:
  60. self.start = float(args[1])
  61. self.end = float(args[0])
  62. else:
  63. raise ValueError("interval takes a maximum of two float values "
  64. "as arguments")
  65. @property
  66. def mid(self):
  67. return (self.start + self.end) / 2.0
  68. @property
  69. def width(self):
  70. return self.end - self.start
  71. def __repr__(self):
  72. return "interval(%f, %f)" % (self.start, self.end)
  73. def __str__(self):
  74. return "[%f, %f]" % (self.start, self.end)
  75. def __lt__(self, other):
  76. if isinstance(other, (int, float)):
  77. if self.end < other:
  78. return intervalMembership(True, self.is_valid)
  79. elif self.start > other:
  80. return intervalMembership(False, self.is_valid)
  81. else:
  82. return intervalMembership(None, self.is_valid)
  83. elif isinstance(other, interval):
  84. valid = fuzzy_and([self.is_valid, other.is_valid])
  85. if self.end < other. start:
  86. return intervalMembership(True, valid)
  87. if self.start > other.end:
  88. return intervalMembership(False, valid)
  89. return intervalMembership(None, valid)
  90. else:
  91. return NotImplemented
  92. def __gt__(self, other):
  93. if isinstance(other, (int, float)):
  94. if self.start > other:
  95. return intervalMembership(True, self.is_valid)
  96. elif self.end < other:
  97. return intervalMembership(False, self.is_valid)
  98. else:
  99. return intervalMembership(None, self.is_valid)
  100. elif isinstance(other, interval):
  101. return other.__lt__(self)
  102. else:
  103. return NotImplemented
  104. def __eq__(self, other):
  105. if isinstance(other, (int, float)):
  106. if self.start == other and self.end == other:
  107. return intervalMembership(True, self.is_valid)
  108. if other in self:
  109. return intervalMembership(None, self.is_valid)
  110. else:
  111. return intervalMembership(False, self.is_valid)
  112. if isinstance(other, interval):
  113. valid = fuzzy_and([self.is_valid, other.is_valid])
  114. if self.start == other.start and self.end == other.end:
  115. return intervalMembership(True, valid)
  116. elif self.__lt__(other)[0] is not None:
  117. return intervalMembership(False, valid)
  118. else:
  119. return intervalMembership(None, valid)
  120. else:
  121. return NotImplemented
  122. def __ne__(self, other):
  123. if isinstance(other, (int, float)):
  124. if self.start == other and self.end == other:
  125. return intervalMembership(False, self.is_valid)
  126. if other in self:
  127. return intervalMembership(None, self.is_valid)
  128. else:
  129. return intervalMembership(True, self.is_valid)
  130. if isinstance(other, interval):
  131. valid = fuzzy_and([self.is_valid, other.is_valid])
  132. if self.start == other.start and self.end == other.end:
  133. return intervalMembership(False, valid)
  134. if not self.__lt__(other)[0] is None:
  135. return intervalMembership(True, valid)
  136. return intervalMembership(None, valid)
  137. else:
  138. return NotImplemented
  139. def __le__(self, other):
  140. if isinstance(other, (int, float)):
  141. if self.end <= other:
  142. return intervalMembership(True, self.is_valid)
  143. if self.start > other:
  144. return intervalMembership(False, self.is_valid)
  145. else:
  146. return intervalMembership(None, self.is_valid)
  147. if isinstance(other, interval):
  148. valid = fuzzy_and([self.is_valid, other.is_valid])
  149. if self.end <= other.start:
  150. return intervalMembership(True, valid)
  151. if self.start > other.end:
  152. return intervalMembership(False, valid)
  153. return intervalMembership(None, valid)
  154. else:
  155. return NotImplemented
  156. def __ge__(self, other):
  157. if isinstance(other, (int, float)):
  158. if self.start >= other:
  159. return intervalMembership(True, self.is_valid)
  160. elif self.end < other:
  161. return intervalMembership(False, self.is_valid)
  162. else:
  163. return intervalMembership(None, self.is_valid)
  164. elif isinstance(other, interval):
  165. return other.__le__(self)
  166. def __add__(self, other):
  167. if isinstance(other, (int, float)):
  168. if self.is_valid:
  169. return interval(self.start + other, self.end + other)
  170. else:
  171. start = self.start + other
  172. end = self.end + other
  173. return interval(start, end, is_valid=self.is_valid)
  174. elif isinstance(other, interval):
  175. start = self.start + other.start
  176. end = self.end + other.end
  177. valid = fuzzy_and([self.is_valid, other.is_valid])
  178. return interval(start, end, is_valid=valid)
  179. else:
  180. return NotImplemented
  181. __radd__ = __add__
  182. def __sub__(self, other):
  183. if isinstance(other, (int, float)):
  184. start = self.start - other
  185. end = self.end - other
  186. return interval(start, end, is_valid=self.is_valid)
  187. elif isinstance(other, interval):
  188. start = self.start - other.end
  189. end = self.end - other.start
  190. valid = fuzzy_and([self.is_valid, other.is_valid])
  191. return interval(start, end, is_valid=valid)
  192. else:
  193. return NotImplemented
  194. def __rsub__(self, other):
  195. if isinstance(other, (int, float)):
  196. start = other - self.end
  197. end = other - self.start
  198. return interval(start, end, is_valid=self.is_valid)
  199. elif isinstance(other, interval):
  200. return other.__sub__(self)
  201. else:
  202. return NotImplemented
  203. def __neg__(self):
  204. if self.is_valid:
  205. return interval(-self.end, -self.start)
  206. else:
  207. return interval(-self.end, -self.start, is_valid=self.is_valid)
  208. def __mul__(self, other):
  209. if isinstance(other, interval):
  210. if self.is_valid is False or other.is_valid is False:
  211. return interval(-float('inf'), float('inf'), is_valid=False)
  212. elif self.is_valid is None or other.is_valid is None:
  213. return interval(-float('inf'), float('inf'), is_valid=None)
  214. else:
  215. inters = []
  216. inters.append(self.start * other.start)
  217. inters.append(self.end * other.start)
  218. inters.append(self.start * other.end)
  219. inters.append(self.end * other.end)
  220. start = min(inters)
  221. end = max(inters)
  222. return interval(start, end)
  223. elif isinstance(other, (int, float)):
  224. return interval(self.start*other, self.end*other, is_valid=self.is_valid)
  225. else:
  226. return NotImplemented
  227. __rmul__ = __mul__
  228. def __contains__(self, other):
  229. if isinstance(other, (int, float)):
  230. return self.start <= other and self.end >= other
  231. else:
  232. return self.start <= other.start and other.end <= self.end
  233. def __rtruediv__(self, other):
  234. if isinstance(other, (int, float)):
  235. other = interval(other)
  236. return other.__truediv__(self)
  237. elif isinstance(other, interval):
  238. return other.__truediv__(self)
  239. else:
  240. return NotImplemented
  241. def __truediv__(self, other):
  242. # Both None and False are handled
  243. if not self.is_valid:
  244. # Don't divide as the value is not valid
  245. return interval(-float('inf'), float('inf'), is_valid=self.is_valid)
  246. if isinstance(other, (int, float)):
  247. if other == 0:
  248. # Divide by zero encountered. valid nowhere
  249. return interval(-float('inf'), float('inf'), is_valid=False)
  250. else:
  251. return interval(self.start / other, self.end / other)
  252. elif isinstance(other, interval):
  253. if other.is_valid is False or self.is_valid is False:
  254. return interval(-float('inf'), float('inf'), is_valid=False)
  255. elif other.is_valid is None or self.is_valid is None:
  256. return interval(-float('inf'), float('inf'), is_valid=None)
  257. else:
  258. # denominator contains both signs, i.e. being divided by zero
  259. # return the whole real line with is_valid = None
  260. if 0 in other:
  261. return interval(-float('inf'), float('inf'), is_valid=None)
  262. # denominator negative
  263. this = self
  264. if other.end < 0:
  265. this = -this
  266. other = -other
  267. # denominator positive
  268. inters = []
  269. inters.append(this.start / other.start)
  270. inters.append(this.end / other.start)
  271. inters.append(this.start / other.end)
  272. inters.append(this.end / other.end)
  273. start = max(inters)
  274. end = min(inters)
  275. return interval(start, end)
  276. else:
  277. return NotImplemented
  278. def __pow__(self, other):
  279. # Implements only power to an integer.
  280. from .lib_interval import exp, log
  281. if not self.is_valid:
  282. return self
  283. if isinstance(other, interval):
  284. return exp(other * log(self))
  285. elif isinstance(other, (float, int)):
  286. if other < 0:
  287. return 1 / self.__pow__(abs(other))
  288. else:
  289. if int(other) == other:
  290. return _pow_int(self, other)
  291. else:
  292. return _pow_float(self, other)
  293. else:
  294. return NotImplemented
  295. def __rpow__(self, other):
  296. if isinstance(other, (float, int)):
  297. if not self.is_valid:
  298. #Don't do anything
  299. return self
  300. elif other < 0:
  301. if self.width > 0:
  302. return interval(-float('inf'), float('inf'), is_valid=False)
  303. else:
  304. power_rational = nsimplify(self.start)
  305. num, denom = power_rational.as_numer_denom()
  306. if denom % 2 == 0:
  307. return interval(-float('inf'), float('inf'),
  308. is_valid=False)
  309. else:
  310. start = -abs(other)**self.start
  311. end = start
  312. return interval(start, end)
  313. else:
  314. return interval(other**self.start, other**self.end)
  315. elif isinstance(other, interval):
  316. return other.__pow__(self)
  317. else:
  318. return NotImplemented
  319. def __hash__(self):
  320. return hash((self.is_valid, self.start, self.end))
  321. def _pow_float(inter, power):
  322. """Evaluates an interval raised to a floating point."""
  323. power_rational = nsimplify(power)
  324. num, denom = power_rational.as_numer_denom()
  325. if num % 2 == 0:
  326. start = abs(inter.start)**power
  327. end = abs(inter.end)**power
  328. if start < 0:
  329. ret = interval(0, max(start, end))
  330. else:
  331. ret = interval(start, end)
  332. return ret
  333. elif denom % 2 == 0:
  334. if inter.end < 0:
  335. return interval(-float('inf'), float('inf'), is_valid=False)
  336. elif inter.start < 0:
  337. return interval(0, inter.end**power, is_valid=None)
  338. else:
  339. return interval(inter.start**power, inter.end**power)
  340. else:
  341. if inter.start < 0:
  342. start = -abs(inter.start)**power
  343. else:
  344. start = inter.start**power
  345. if inter.end < 0:
  346. end = -abs(inter.end)**power
  347. else:
  348. end = inter.end**power
  349. return interval(start, end, is_valid=inter.is_valid)
  350. def _pow_int(inter, power):
  351. """Evaluates an interval raised to an integer power"""
  352. power = int(power)
  353. if power & 1:
  354. return interval(inter.start**power, inter.end**power)
  355. else:
  356. if inter.start < 0 and inter.end > 0:
  357. start = 0
  358. end = max(inter.start**power, inter.end**power)
  359. return interval(start, end)
  360. else:
  361. return interval(inter.start**power, inter.end**power)