util.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. """Utility functions for geometrical entities.
  2. Contains
  3. ========
  4. intersection
  5. convex_hull
  6. closest_points
  7. farthest_points
  8. are_coplanar
  9. are_similar
  10. """
  11. from collections import deque
  12. from math import sqrt as _sqrt
  13. from sympy import nsimplify
  14. from .entity import GeometryEntity
  15. from .exceptions import GeometryError
  16. from .point import Point, Point2D, Point3D
  17. from sympy.core.containers import OrderedSet
  18. from sympy.core.exprtools import factor_terms
  19. from sympy.core.function import Function, expand_mul
  20. from sympy.core.numbers import Float
  21. from sympy.core.sorting import ordered
  22. from sympy.core.symbol import Symbol
  23. from sympy.core.singleton import S
  24. from sympy.polys.polytools import cancel
  25. from sympy.functions.elementary.miscellaneous import sqrt
  26. from sympy.utilities.iterables import is_sequence
  27. from mpmath.libmp.libmpf import prec_to_dps
  28. def find(x, equation):
  29. """
  30. Checks whether a Symbol matching ``x`` is present in ``equation``
  31. or not. If present, the matching symbol is returned, else a
  32. ValueError is raised. If ``x`` is a string the matching symbol
  33. will have the same name; if ``x`` is a Symbol then it will be
  34. returned if found.
  35. Examples
  36. ========
  37. >>> from sympy.geometry.util import find
  38. >>> from sympy import Dummy
  39. >>> from sympy.abc import x
  40. >>> find('x', x)
  41. x
  42. >>> find('x', Dummy('x'))
  43. _x
  44. The dummy symbol is returned since it has a matching name:
  45. >>> _.name == 'x'
  46. True
  47. >>> find(x, Dummy('x'))
  48. Traceback (most recent call last):
  49. ...
  50. ValueError: could not find x
  51. """
  52. free = equation.free_symbols
  53. xs = [i for i in free if (i.name if isinstance(x, str) else i) == x]
  54. if not xs:
  55. raise ValueError('could not find %s' % x)
  56. if len(xs) != 1:
  57. raise ValueError('ambiguous %s' % x)
  58. return xs[0]
  59. def _ordered_points(p):
  60. """Return the tuple of points sorted numerically according to args"""
  61. return tuple(sorted(p, key=lambda x: x.args))
  62. def are_coplanar(*e):
  63. """ Returns True if the given entities are coplanar otherwise False
  64. Parameters
  65. ==========
  66. e: entities to be checked for being coplanar
  67. Returns
  68. =======
  69. Boolean
  70. Examples
  71. ========
  72. >>> from sympy import Point3D, Line3D
  73. >>> from sympy.geometry.util import are_coplanar
  74. >>> a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
  75. >>> b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
  76. >>> c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
  77. >>> are_coplanar(a, b, c)
  78. False
  79. """
  80. from .line import LinearEntity3D
  81. from .plane import Plane
  82. # XXX update tests for coverage
  83. e = set(e)
  84. # first work with a Plane if present
  85. for i in list(e):
  86. if isinstance(i, Plane):
  87. e.remove(i)
  88. return all(p.is_coplanar(i) for p in e)
  89. if all(isinstance(i, Point3D) for i in e):
  90. if len(e) < 3:
  91. return False
  92. # remove pts that are collinear with 2 pts
  93. a, b = e.pop(), e.pop()
  94. for i in list(e):
  95. if Point3D.are_collinear(a, b, i):
  96. e.remove(i)
  97. if not e:
  98. return False
  99. else:
  100. # define a plane
  101. p = Plane(a, b, e.pop())
  102. for i in e:
  103. if i not in p:
  104. return False
  105. return True
  106. else:
  107. pt3d = []
  108. for i in e:
  109. if isinstance(i, Point3D):
  110. pt3d.append(i)
  111. elif isinstance(i, LinearEntity3D):
  112. pt3d.extend(i.args)
  113. elif isinstance(i, GeometryEntity): # XXX we should have a GeometryEntity3D class so we can tell the difference between 2D and 3D -- here we just want to deal with 2D objects; if new 3D objects are encountered that we didn't handle above, an error should be raised
  114. # all 2D objects have some Point that defines them; so convert those points to 3D pts by making z=0
  115. for p in i.args:
  116. if isinstance(p, Point):
  117. pt3d.append(Point3D(*(p.args + (0,))))
  118. return are_coplanar(*pt3d)
  119. def are_similar(e1, e2):
  120. """Are two geometrical entities similar.
  121. Can one geometrical entity be uniformly scaled to the other?
  122. Parameters
  123. ==========
  124. e1 : GeometryEntity
  125. e2 : GeometryEntity
  126. Returns
  127. =======
  128. are_similar : boolean
  129. Raises
  130. ======
  131. GeometryError
  132. When `e1` and `e2` cannot be compared.
  133. Notes
  134. =====
  135. If the two objects are equal then they are similar.
  136. See Also
  137. ========
  138. sympy.geometry.entity.GeometryEntity.is_similar
  139. Examples
  140. ========
  141. >>> from sympy import Point, Circle, Triangle, are_similar
  142. >>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3)
  143. >>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
  144. >>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2))
  145. >>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1))
  146. >>> are_similar(t1, t2)
  147. True
  148. >>> are_similar(t1, t3)
  149. False
  150. """
  151. if e1 == e2:
  152. return True
  153. is_similar1 = getattr(e1, 'is_similar', None)
  154. if is_similar1:
  155. return is_similar1(e2)
  156. is_similar2 = getattr(e2, 'is_similar', None)
  157. if is_similar2:
  158. return is_similar2(e1)
  159. n1 = e1.__class__.__name__
  160. n2 = e2.__class__.__name__
  161. raise GeometryError(
  162. "Cannot test similarity between %s and %s" % (n1, n2))
  163. def centroid(*args):
  164. """Find the centroid (center of mass) of the collection containing only Points,
  165. Segments or Polygons. The centroid is the weighted average of the individual centroid
  166. where the weights are the lengths (of segments) or areas (of polygons).
  167. Overlapping regions will add to the weight of that region.
  168. If there are no objects (or a mixture of objects) then None is returned.
  169. See Also
  170. ========
  171. sympy.geometry.point.Point, sympy.geometry.line.Segment,
  172. sympy.geometry.polygon.Polygon
  173. Examples
  174. ========
  175. >>> from sympy import Point, Segment, Polygon
  176. >>> from sympy.geometry.util import centroid
  177. >>> p = Polygon((0, 0), (10, 0), (10, 10))
  178. >>> q = p.translate(0, 20)
  179. >>> p.centroid, q.centroid
  180. (Point2D(20/3, 10/3), Point2D(20/3, 70/3))
  181. >>> centroid(p, q)
  182. Point2D(20/3, 40/3)
  183. >>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))
  184. >>> centroid(p, q)
  185. Point2D(1, 2 - sqrt(2))
  186. >>> centroid(Point(0, 0), Point(2, 0))
  187. Point2D(1, 0)
  188. Stacking 3 polygons on top of each other effectively triples the
  189. weight of that polygon:
  190. >>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))
  191. >>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))
  192. >>> centroid(p, q)
  193. Point2D(3/2, 1/2)
  194. >>> centroid(p, p, p, q) # centroid x-coord shifts left
  195. Point2D(11/10, 1/2)
  196. Stacking the squares vertically above and below p has the same
  197. effect:
  198. >>> centroid(p, p.translate(0, 1), p.translate(0, -1), q)
  199. Point2D(11/10, 1/2)
  200. """
  201. from .line import Segment
  202. from .polygon import Polygon
  203. if args:
  204. if all(isinstance(g, Point) for g in args):
  205. c = Point(0, 0)
  206. for g in args:
  207. c += g
  208. den = len(args)
  209. elif all(isinstance(g, Segment) for g in args):
  210. c = Point(0, 0)
  211. L = 0
  212. for g in args:
  213. l = g.length
  214. c += g.midpoint*l
  215. L += l
  216. den = L
  217. elif all(isinstance(g, Polygon) for g in args):
  218. c = Point(0, 0)
  219. A = 0
  220. for g in args:
  221. a = g.area
  222. c += g.centroid*a
  223. A += a
  224. den = A
  225. c /= den
  226. return c.func(*[i.simplify() for i in c.args])
  227. def closest_points(*args):
  228. """Return the subset of points from a set of points that were
  229. the closest to each other in the 2D plane.
  230. Parameters
  231. ==========
  232. args
  233. A collection of Points on 2D plane.
  234. Notes
  235. =====
  236. This can only be performed on a set of points whose coordinates can
  237. be ordered on the number line. If there are no ties then a single
  238. pair of Points will be in the set.
  239. Examples
  240. ========
  241. >>> from sympy import closest_points, Triangle
  242. >>> Triangle(sss=(3, 4, 5)).args
  243. (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
  244. >>> closest_points(*_)
  245. {(Point2D(0, 0), Point2D(3, 0))}
  246. References
  247. ==========
  248. .. [1] https://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html
  249. .. [2] Sweep line algorithm
  250. https://en.wikipedia.org/wiki/Sweep_line_algorithm
  251. """
  252. p = [Point2D(i) for i in set(args)]
  253. if len(p) < 2:
  254. raise ValueError('At least 2 distinct points must be given.')
  255. try:
  256. p.sort(key=lambda x: x.args)
  257. except TypeError:
  258. raise ValueError("The points could not be sorted.")
  259. if not all(i.is_Rational for j in p for i in j.args):
  260. def hypot(x, y):
  261. arg = x*x + y*y
  262. if arg.is_Rational:
  263. return _sqrt(arg)
  264. return sqrt(arg)
  265. else:
  266. from math import hypot
  267. rv = [(0, 1)]
  268. best_dist = hypot(p[1].x - p[0].x, p[1].y - p[0].y)
  269. left = 0
  270. box = deque([0, 1])
  271. for i in range(2, len(p)):
  272. while left < i and p[i][0] - p[left][0] > best_dist:
  273. box.popleft()
  274. left += 1
  275. for j in box:
  276. d = hypot(p[i].x - p[j].x, p[i].y - p[j].y)
  277. if d < best_dist:
  278. rv = [(j, i)]
  279. elif d == best_dist:
  280. rv.append((j, i))
  281. else:
  282. continue
  283. best_dist = d
  284. box.append(i)
  285. return {tuple([p[i] for i in pair]) for pair in rv}
  286. def convex_hull(*args, polygon=True):
  287. """The convex hull surrounding the Points contained in the list of entities.
  288. Parameters
  289. ==========
  290. args : a collection of Points, Segments and/or Polygons
  291. Optional parameters
  292. ===================
  293. polygon : Boolean. If True, returns a Polygon, if false a tuple, see below.
  294. Default is True.
  295. Returns
  296. =======
  297. convex_hull : Polygon if ``polygon`` is True else as a tuple `(U, L)` where
  298. ``L`` and ``U`` are the lower and upper hulls, respectively.
  299. Notes
  300. =====
  301. This can only be performed on a set of points whose coordinates can
  302. be ordered on the number line.
  303. See Also
  304. ========
  305. sympy.geometry.point.Point, sympy.geometry.polygon.Polygon
  306. Examples
  307. ========
  308. >>> from sympy import convex_hull
  309. >>> points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
  310. >>> convex_hull(*points)
  311. Polygon(Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4))
  312. >>> convex_hull(*points, **dict(polygon=False))
  313. ([Point2D(-5, 2), Point2D(15, 4)],
  314. [Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)])
  315. References
  316. ==========
  317. .. [1] https://en.wikipedia.org/wiki/Graham_scan
  318. .. [2] Andrew's Monotone Chain Algorithm
  319. (A.M. Andrew,
  320. "Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979)
  321. https://web.archive.org/web/20210511015444/http://geomalgorithms.com/a10-_hull-1.html
  322. """
  323. from .line import Segment
  324. from .polygon import Polygon
  325. p = OrderedSet()
  326. for e in args:
  327. if not isinstance(e, GeometryEntity):
  328. try:
  329. e = Point(e)
  330. except NotImplementedError:
  331. raise ValueError('%s is not a GeometryEntity and cannot be made into Point' % str(e))
  332. if isinstance(e, Point):
  333. p.add(e)
  334. elif isinstance(e, Segment):
  335. p.update(e.points)
  336. elif isinstance(e, Polygon):
  337. p.update(e.vertices)
  338. else:
  339. raise NotImplementedError(
  340. 'Convex hull for %s not implemented.' % type(e))
  341. # make sure all our points are of the same dimension
  342. if any(len(x) != 2 for x in p):
  343. raise ValueError('Can only compute the convex hull in two dimensions')
  344. p = list(p)
  345. if len(p) == 1:
  346. return p[0] if polygon else (p[0], None)
  347. elif len(p) == 2:
  348. s = Segment(p[0], p[1])
  349. return s if polygon else (s, None)
  350. def _orientation(p, q, r):
  351. '''Return positive if p-q-r are clockwise, neg if ccw, zero if
  352. collinear.'''
  353. return (q.y - p.y)*(r.x - p.x) - (q.x - p.x)*(r.y - p.y)
  354. # scan to find upper and lower convex hulls of a set of 2d points.
  355. U = []
  356. L = []
  357. try:
  358. p.sort(key=lambda x: x.args)
  359. except TypeError:
  360. raise ValueError("The points could not be sorted.")
  361. for p_i in p:
  362. while len(U) > 1 and _orientation(U[-2], U[-1], p_i) <= 0:
  363. U.pop()
  364. while len(L) > 1 and _orientation(L[-2], L[-1], p_i) >= 0:
  365. L.pop()
  366. U.append(p_i)
  367. L.append(p_i)
  368. U.reverse()
  369. convexHull = tuple(L + U[1:-1])
  370. if len(convexHull) == 2:
  371. s = Segment(convexHull[0], convexHull[1])
  372. return s if polygon else (s, None)
  373. if polygon:
  374. return Polygon(*convexHull)
  375. else:
  376. U.reverse()
  377. return (U, L)
  378. def farthest_points(*args):
  379. """Return the subset of points from a set of points that were
  380. the furthest apart from each other in the 2D plane.
  381. Parameters
  382. ==========
  383. args
  384. A collection of Points on 2D plane.
  385. Notes
  386. =====
  387. This can only be performed on a set of points whose coordinates can
  388. be ordered on the number line. If there are no ties then a single
  389. pair of Points will be in the set.
  390. Examples
  391. ========
  392. >>> from sympy.geometry import farthest_points, Triangle
  393. >>> Triangle(sss=(3, 4, 5)).args
  394. (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
  395. >>> farthest_points(*_)
  396. {(Point2D(0, 0), Point2D(3, 4))}
  397. References
  398. ==========
  399. .. [1] https://code.activestate.com/recipes/117225-convex-hull-and-diameter-of-2d-point-sets/
  400. .. [2] Rotating Callipers Technique
  401. https://en.wikipedia.org/wiki/Rotating_calipers
  402. """
  403. def rotatingCalipers(Points):
  404. U, L = convex_hull(*Points, **{"polygon": False})
  405. if L is None:
  406. if isinstance(U, Point):
  407. raise ValueError('At least two distinct points must be given.')
  408. yield U.args
  409. else:
  410. i = 0
  411. j = len(L) - 1
  412. while i < len(U) - 1 or j > 0:
  413. yield U[i], L[j]
  414. # if all the way through one side of hull, advance the other side
  415. if i == len(U) - 1:
  416. j -= 1
  417. elif j == 0:
  418. i += 1
  419. # still points left on both lists, compare slopes of next hull edges
  420. # being careful to avoid divide-by-zero in slope calculation
  421. elif (U[i+1].y - U[i].y) * (L[j].x - L[j-1].x) > \
  422. (L[j].y - L[j-1].y) * (U[i+1].x - U[i].x):
  423. i += 1
  424. else:
  425. j -= 1
  426. p = [Point2D(i) for i in set(args)]
  427. if not all(i.is_Rational for j in p for i in j.args):
  428. def hypot(x, y):
  429. arg = x*x + y*y
  430. if arg.is_Rational:
  431. return _sqrt(arg)
  432. return sqrt(arg)
  433. else:
  434. from math import hypot
  435. rv = []
  436. diam = 0
  437. for pair in rotatingCalipers(args):
  438. h, q = _ordered_points(pair)
  439. d = hypot(h.x - q.x, h.y - q.y)
  440. if d > diam:
  441. rv = [(h, q)]
  442. elif d == diam:
  443. rv.append((h, q))
  444. else:
  445. continue
  446. diam = d
  447. return set(rv)
  448. def idiff(eq, y, x, n=1):
  449. """Return ``dy/dx`` assuming that ``eq == 0``.
  450. Parameters
  451. ==========
  452. y : the dependent variable or a list of dependent variables (with y first)
  453. x : the variable that the derivative is being taken with respect to
  454. n : the order of the derivative (default is 1)
  455. Examples
  456. ========
  457. >>> from sympy.abc import x, y, a
  458. >>> from sympy.geometry.util import idiff
  459. >>> circ = x**2 + y**2 - 4
  460. >>> idiff(circ, y, x)
  461. -x/y
  462. >>> idiff(circ, y, x, 2).simplify()
  463. (-x**2 - y**2)/y**3
  464. Here, ``a`` is assumed to be independent of ``x``:
  465. >>> idiff(x + a + y, y, x)
  466. -1
  467. Now the x-dependence of ``a`` is made explicit by listing ``a`` after
  468. ``y`` in a list.
  469. >>> idiff(x + a + y, [y, a], x)
  470. -Derivative(a, x) - 1
  471. See Also
  472. ========
  473. sympy.core.function.Derivative: represents unevaluated derivatives
  474. sympy.core.function.diff: explicitly differentiates wrt symbols
  475. """
  476. if is_sequence(y):
  477. dep = set(y)
  478. y = y[0]
  479. elif isinstance(y, Symbol):
  480. dep = {y}
  481. elif isinstance(y, Function):
  482. pass
  483. else:
  484. raise ValueError("expecting x-dependent symbol(s) or function(s) but got: %s" % y)
  485. f = {s: Function(s.name)(x) for s in eq.free_symbols
  486. if s != x and s in dep}
  487. if isinstance(y, Symbol):
  488. dydx = Function(y.name)(x).diff(x)
  489. else:
  490. dydx = y.diff(x)
  491. eq = eq.subs(f)
  492. derivs = {}
  493. for i in range(n):
  494. # equation will be linear in dydx, a*dydx + b, so dydx = -b/a
  495. deq = eq.diff(x)
  496. b = deq.xreplace({dydx: S.Zero})
  497. a = (deq - b).xreplace({dydx: S.One})
  498. yp = factor_terms(expand_mul(cancel((-b/a).subs(derivs)), deep=False))
  499. if i == n - 1:
  500. return yp.subs([(v, k) for k, v in f.items()])
  501. derivs[dydx] = yp
  502. eq = dydx - yp
  503. dydx = dydx.diff(x)
  504. def intersection(*entities, pairwise=False, **kwargs):
  505. """The intersection of a collection of GeometryEntity instances.
  506. Parameters
  507. ==========
  508. entities : sequence of GeometryEntity
  509. pairwise (keyword argument) : Can be either True or False
  510. Returns
  511. =======
  512. intersection : list of GeometryEntity
  513. Raises
  514. ======
  515. NotImplementedError
  516. When unable to calculate intersection.
  517. Notes
  518. =====
  519. The intersection of any geometrical entity with itself should return
  520. a list with one item: the entity in question.
  521. An intersection requires two or more entities. If only a single
  522. entity is given then the function will return an empty list.
  523. It is possible for `intersection` to miss intersections that one
  524. knows exists because the required quantities were not fully
  525. simplified internally.
  526. Reals should be converted to Rationals, e.g. Rational(str(real_num))
  527. or else failures due to floating point issues may result.
  528. Case 1: When the keyword argument 'pairwise' is False (default value):
  529. In this case, the function returns a list of intersections common to
  530. all entities.
  531. Case 2: When the keyword argument 'pairwise' is True:
  532. In this case, the functions returns a list intersections that occur
  533. between any pair of entities.
  534. See Also
  535. ========
  536. sympy.geometry.entity.GeometryEntity.intersection
  537. Examples
  538. ========
  539. >>> from sympy import Ray, Circle, intersection
  540. >>> c = Circle((0, 1), 1)
  541. >>> intersection(c, c.center)
  542. []
  543. >>> right = Ray((0, 0), (1, 0))
  544. >>> up = Ray((0, 0), (0, 1))
  545. >>> intersection(c, right, up)
  546. [Point2D(0, 0)]
  547. >>> intersection(c, right, up, pairwise=True)
  548. [Point2D(0, 0), Point2D(0, 2)]
  549. >>> left = Ray((1, 0), (0, 0))
  550. >>> intersection(right, left)
  551. [Segment2D(Point2D(0, 0), Point2D(1, 0))]
  552. """
  553. if len(entities) <= 1:
  554. return []
  555. entities = list(entities)
  556. prec = None
  557. for i, e in enumerate(entities):
  558. if not isinstance(e, GeometryEntity):
  559. # entities may be an immutable tuple
  560. e = Point(e)
  561. # convert to exact Rationals
  562. d = {}
  563. for f in e.atoms(Float):
  564. prec = f._prec if prec is None else min(f._prec, prec)
  565. d.setdefault(f, nsimplify(f, rational=True))
  566. entities[i] = e.xreplace(d)
  567. if not pairwise:
  568. # find the intersection common to all objects
  569. res = entities[0].intersection(entities[1])
  570. for entity in entities[2:]:
  571. newres = []
  572. for x in res:
  573. newres.extend(x.intersection(entity))
  574. res = newres
  575. else:
  576. # find all pairwise intersections
  577. ans = []
  578. for j in range(len(entities)):
  579. for k in range(j + 1, len(entities)):
  580. ans.extend(intersection(entities[j], entities[k]))
  581. res = list(ordered(set(ans)))
  582. # convert back to Floats
  583. if prec is not None:
  584. p = prec_to_dps(prec)
  585. res = [i.n(p) for i in res]
  586. return res