polyroots.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. """Algorithms for computing symbolic roots of polynomials. """
  2. import math
  3. from functools import reduce
  4. from sympy.core import S, I, pi
  5. from sympy.core.exprtools import factor_terms
  6. from sympy.core.function import _mexpand
  7. from sympy.core.logic import fuzzy_not
  8. from sympy.core.mul import expand_2arg, Mul
  9. from sympy.core.numbers import Rational, igcd, comp
  10. from sympy.core.power import Pow
  11. from sympy.core.relational import Eq
  12. from sympy.core.sorting import ordered
  13. from sympy.core.symbol import Dummy, Symbol, symbols
  14. from sympy.core.sympify import sympify
  15. from sympy.functions import exp, sqrt, im, cos, acos, Piecewise
  16. from sympy.functions.elementary.miscellaneous import root
  17. from sympy.ntheory import divisors, isprime, nextprime
  18. from sympy.polys.domains import EX
  19. from sympy.polys.polyerrors import (PolynomialError, GeneratorsNeeded,
  20. DomainError)
  21. from sympy.polys.polyquinticconst import PolyQuintic
  22. from sympy.polys.polytools import Poly, cancel, factor, gcd_list, discriminant
  23. from sympy.polys.rationaltools import together
  24. from sympy.polys.specialpolys import cyclotomic_poly
  25. from sympy.simplify.simplify import simplify, powsimp
  26. from sympy.utilities import public
  27. def roots_linear(f):
  28. """Returns a list of roots of a linear polynomial."""
  29. r = -f.nth(0)/f.nth(1)
  30. dom = f.get_domain()
  31. if not dom.is_Numerical:
  32. if dom.is_Composite:
  33. r = factor(r)
  34. else:
  35. r = simplify(r)
  36. return [r]
  37. def roots_quadratic(f):
  38. """Returns a list of roots of a quadratic polynomial. If the domain is ZZ
  39. then the roots will be sorted with negatives coming before positives.
  40. The ordering will be the same for any numerical coefficients as long as
  41. the assumptions tested are correct, otherwise the ordering will not be
  42. sorted (but will be canonical).
  43. """
  44. a, b, c = f.all_coeffs()
  45. dom = f.get_domain()
  46. def _sqrt(d):
  47. # remove squares from square root since both will be represented
  48. # in the results; a similar thing is happening in roots() but
  49. # must be duplicated here because not all quadratics are binomials
  50. co = []
  51. other = []
  52. for di in Mul.make_args(d):
  53. if di.is_Pow and di.exp.is_Integer and di.exp % 2 == 0:
  54. co.append(Pow(di.base, di.exp//2))
  55. else:
  56. other.append(di)
  57. if co:
  58. d = Mul(*other)
  59. co = Mul(*co)
  60. return co*sqrt(d)
  61. return sqrt(d)
  62. def _simplify(expr):
  63. if dom.is_Composite:
  64. return factor(expr)
  65. else:
  66. return simplify(expr)
  67. if c is S.Zero:
  68. r0, r1 = S.Zero, -b/a
  69. if not dom.is_Numerical:
  70. r1 = _simplify(r1)
  71. elif r1.is_negative:
  72. r0, r1 = r1, r0
  73. elif b is S.Zero:
  74. r = -c/a
  75. if not dom.is_Numerical:
  76. r = _simplify(r)
  77. R = _sqrt(r)
  78. r0 = -R
  79. r1 = R
  80. else:
  81. d = b**2 - 4*a*c
  82. A = 2*a
  83. B = -b/A
  84. if not dom.is_Numerical:
  85. d = _simplify(d)
  86. B = _simplify(B)
  87. D = factor_terms(_sqrt(d)/A)
  88. r0 = B - D
  89. r1 = B + D
  90. if a.is_negative:
  91. r0, r1 = r1, r0
  92. elif not dom.is_Numerical:
  93. r0, r1 = [expand_2arg(i) for i in (r0, r1)]
  94. return [r0, r1]
  95. def roots_cubic(f, trig=False):
  96. """Returns a list of roots of a cubic polynomial.
  97. References
  98. ==========
  99. [1] https://en.wikipedia.org/wiki/Cubic_function, General formula for roots,
  100. (accessed November 17, 2014).
  101. """
  102. if trig:
  103. a, b, c, d = f.all_coeffs()
  104. p = (3*a*c - b**2)/(3*a**2)
  105. q = (2*b**3 - 9*a*b*c + 27*a**2*d)/(27*a**3)
  106. D = 18*a*b*c*d - 4*b**3*d + b**2*c**2 - 4*a*c**3 - 27*a**2*d**2
  107. if (D > 0) == True:
  108. rv = []
  109. for k in range(3):
  110. rv.append(2*sqrt(-p/3)*cos(acos(q/p*sqrt(-3/p)*Rational(3, 2))/3 - k*pi*Rational(2, 3)))
  111. return [i - b/3/a for i in rv]
  112. # a*x**3 + b*x**2 + c*x + d -> x**3 + a*x**2 + b*x + c
  113. _, a, b, c = f.monic().all_coeffs()
  114. if c is S.Zero:
  115. x1, x2 = roots([1, a, b], multiple=True)
  116. return [x1, S.Zero, x2]
  117. # x**3 + a*x**2 + b*x + c -> u**3 + p*u + q
  118. p = b - a**2/3
  119. q = c - a*b/3 + 2*a**3/27
  120. pon3 = p/3
  121. aon3 = a/3
  122. u1 = None
  123. if p is S.Zero:
  124. if q is S.Zero:
  125. return [-aon3]*3
  126. u1 = -root(q, 3) if q.is_positive else root(-q, 3)
  127. elif q is S.Zero:
  128. y1, y2 = roots([1, 0, p], multiple=True)
  129. return [tmp - aon3 for tmp in [y1, S.Zero, y2]]
  130. elif q.is_real and q.is_negative:
  131. u1 = -root(-q/2 + sqrt(q**2/4 + pon3**3), 3)
  132. coeff = I*sqrt(3)/2
  133. if u1 is None:
  134. u1 = S.One
  135. u2 = Rational(-1, 2) + coeff
  136. u3 = Rational(-1, 2) - coeff
  137. b, c, d = a, b, c # a, b, c, d = S.One, a, b, c
  138. D0 = b**2 - 3*c # b**2 - 3*a*c
  139. D1 = 2*b**3 - 9*b*c + 27*d # 2*b**3 - 9*a*b*c + 27*a**2*d
  140. C = root((D1 + sqrt(D1**2 - 4*D0**3))/2, 3)
  141. return [-(b + uk*C + D0/C/uk)/3 for uk in [u1, u2, u3]] # -(b + uk*C + D0/C/uk)/3/a
  142. u2 = u1*(Rational(-1, 2) + coeff)
  143. u3 = u1*(Rational(-1, 2) - coeff)
  144. if p is S.Zero:
  145. return [u1 - aon3, u2 - aon3, u3 - aon3]
  146. soln = [
  147. -u1 + pon3/u1 - aon3,
  148. -u2 + pon3/u2 - aon3,
  149. -u3 + pon3/u3 - aon3
  150. ]
  151. return soln
  152. def _roots_quartic_euler(p, q, r, a):
  153. """
  154. Descartes-Euler solution of the quartic equation
  155. Parameters
  156. ==========
  157. p, q, r: coefficients of ``x**4 + p*x**2 + q*x + r``
  158. a: shift of the roots
  159. Notes
  160. =====
  161. This is a helper function for ``roots_quartic``.
  162. Look for solutions of the form ::
  163. ``x1 = sqrt(R) - sqrt(A + B*sqrt(R))``
  164. ``x2 = -sqrt(R) - sqrt(A - B*sqrt(R))``
  165. ``x3 = -sqrt(R) + sqrt(A - B*sqrt(R))``
  166. ``x4 = sqrt(R) + sqrt(A + B*sqrt(R))``
  167. To satisfy the quartic equation one must have
  168. ``p = -2*(R + A); q = -4*B*R; r = (R - A)**2 - B**2*R``
  169. so that ``R`` must satisfy the Descartes-Euler resolvent equation
  170. ``64*R**3 + 32*p*R**2 + (4*p**2 - 16*r)*R - q**2 = 0``
  171. If the resolvent does not have a rational solution, return None;
  172. in that case it is likely that the Ferrari method gives a simpler
  173. solution.
  174. Examples
  175. ========
  176. >>> from sympy import S
  177. >>> from sympy.polys.polyroots import _roots_quartic_euler
  178. >>> p, q, r = -S(64)/5, -S(512)/125, -S(1024)/3125
  179. >>> _roots_quartic_euler(p, q, r, S(0))[0]
  180. -sqrt(32*sqrt(5)/125 + 16/5) + 4*sqrt(5)/5
  181. """
  182. # solve the resolvent equation
  183. x = Dummy('x')
  184. eq = 64*x**3 + 32*p*x**2 + (4*p**2 - 16*r)*x - q**2
  185. xsols = list(roots(Poly(eq, x), cubics=False).keys())
  186. xsols = [sol for sol in xsols if sol.is_rational and sol.is_nonzero]
  187. if not xsols:
  188. return None
  189. R = max(xsols)
  190. c1 = sqrt(R)
  191. B = -q*c1/(4*R)
  192. A = -R - p/2
  193. c2 = sqrt(A + B)
  194. c3 = sqrt(A - B)
  195. return [c1 - c2 - a, -c1 - c3 - a, -c1 + c3 - a, c1 + c2 - a]
  196. def roots_quartic(f):
  197. r"""
  198. Returns a list of roots of a quartic polynomial.
  199. There are many references for solving quartic expressions available [1-5].
  200. This reviewer has found that many of them require one to select from among
  201. 2 or more possible sets of solutions and that some solutions work when one
  202. is searching for real roots but do not work when searching for complex roots
  203. (though this is not always stated clearly). The following routine has been
  204. tested and found to be correct for 0, 2 or 4 complex roots.
  205. The quasisymmetric case solution [6] looks for quartics that have the form
  206. `x**4 + A*x**3 + B*x**2 + C*x + D = 0` where `(C/A)**2 = D`.
  207. Although no general solution that is always applicable for all
  208. coefficients is known to this reviewer, certain conditions are tested
  209. to determine the simplest 4 expressions that can be returned:
  210. 1) `f = c + a*(a**2/8 - b/2) == 0`
  211. 2) `g = d - a*(a*(3*a**2/256 - b/16) + c/4) = 0`
  212. 3) if `f != 0` and `g != 0` and `p = -d + a*c/4 - b**2/12` then
  213. a) `p == 0`
  214. b) `p != 0`
  215. Examples
  216. ========
  217. >>> from sympy import Poly
  218. >>> from sympy.polys.polyroots import roots_quartic
  219. >>> r = roots_quartic(Poly('x**4-6*x**3+17*x**2-26*x+20'))
  220. >>> # 4 complex roots: 1+-I*sqrt(3), 2+-I
  221. >>> sorted(str(tmp.evalf(n=2)) for tmp in r)
  222. ['1.0 + 1.7*I', '1.0 - 1.7*I', '2.0 + 1.0*I', '2.0 - 1.0*I']
  223. References
  224. ==========
  225. 1. http://mathforum.org/dr.math/faq/faq.cubic.equations.html
  226. 2. https://en.wikipedia.org/wiki/Quartic_function#Summary_of_Ferrari.27s_method
  227. 3. http://planetmath.org/encyclopedia/GaloisTheoreticDerivationOfTheQuarticFormula.html
  228. 4. http://staff.bath.ac.uk/masjhd/JHD-CA.pdf
  229. 5. http://www.albmath.org/files/Math_5713.pdf
  230. 6. http://www.statemaster.com/encyclopedia/Quartic-equation
  231. 7. eqworld.ipmnet.ru/en/solutions/ae/ae0108.pdf
  232. """
  233. _, a, b, c, d = f.monic().all_coeffs()
  234. if not d:
  235. return [S.Zero] + roots([1, a, b, c], multiple=True)
  236. elif (c/a)**2 == d:
  237. x, m = f.gen, c/a
  238. g = Poly(x**2 + a*x + b - 2*m, x)
  239. z1, z2 = roots_quadratic(g)
  240. h1 = Poly(x**2 - z1*x + m, x)
  241. h2 = Poly(x**2 - z2*x + m, x)
  242. r1 = roots_quadratic(h1)
  243. r2 = roots_quadratic(h2)
  244. return r1 + r2
  245. else:
  246. a2 = a**2
  247. e = b - 3*a2/8
  248. f = _mexpand(c + a*(a2/8 - b/2))
  249. aon4 = a/4
  250. g = _mexpand(d - aon4*(a*(3*a2/64 - b/4) + c))
  251. if f.is_zero:
  252. y1, y2 = [sqrt(tmp) for tmp in
  253. roots([1, e, g], multiple=True)]
  254. return [tmp - aon4 for tmp in [-y1, -y2, y1, y2]]
  255. if g.is_zero:
  256. y = [S.Zero] + roots([1, 0, e, f], multiple=True)
  257. return [tmp - aon4 for tmp in y]
  258. else:
  259. # Descartes-Euler method, see [7]
  260. sols = _roots_quartic_euler(e, f, g, aon4)
  261. if sols:
  262. return sols
  263. # Ferrari method, see [1, 2]
  264. p = -e**2/12 - g
  265. q = -e**3/108 + e*g/3 - f**2/8
  266. TH = Rational(1, 3)
  267. def _ans(y):
  268. w = sqrt(e + 2*y)
  269. arg1 = 3*e + 2*y
  270. arg2 = 2*f/w
  271. ans = []
  272. for s in [-1, 1]:
  273. root = sqrt(-(arg1 + s*arg2))
  274. for t in [-1, 1]:
  275. ans.append((s*w - t*root)/2 - aon4)
  276. return ans
  277. # whether a Piecewise is returned or not
  278. # depends on knowing p, so try to put
  279. # in a simple form
  280. p = _mexpand(p)
  281. # p == 0 case
  282. y1 = e*Rational(-5, 6) - q**TH
  283. if p.is_zero:
  284. return _ans(y1)
  285. # if p != 0 then u below is not 0
  286. root = sqrt(q**2/4 + p**3/27)
  287. r = -q/2 + root # or -q/2 - root
  288. u = r**TH # primary root of solve(x**3 - r, x)
  289. y2 = e*Rational(-5, 6) + u - p/u/3
  290. if fuzzy_not(p.is_zero):
  291. return _ans(y2)
  292. # sort it out once they know the values of the coefficients
  293. return [Piecewise((a1, Eq(p, 0)), (a2, True))
  294. for a1, a2 in zip(_ans(y1), _ans(y2))]
  295. def roots_binomial(f):
  296. """Returns a list of roots of a binomial polynomial. If the domain is ZZ
  297. then the roots will be sorted with negatives coming before positives.
  298. The ordering will be the same for any numerical coefficients as long as
  299. the assumptions tested are correct, otherwise the ordering will not be
  300. sorted (but will be canonical).
  301. """
  302. n = f.degree()
  303. a, b = f.nth(n), f.nth(0)
  304. base = -cancel(b/a)
  305. alpha = root(base, n)
  306. if alpha.is_number:
  307. alpha = alpha.expand(complex=True)
  308. # define some parameters that will allow us to order the roots.
  309. # If the domain is ZZ this is guaranteed to return roots sorted
  310. # with reals before non-real roots and non-real sorted according
  311. # to real part and imaginary part, e.g. -1, 1, -1 + I, 2 - I
  312. neg = base.is_negative
  313. even = n % 2 == 0
  314. if neg:
  315. if even == True and (base + 1).is_positive:
  316. big = True
  317. else:
  318. big = False
  319. # get the indices in the right order so the computed
  320. # roots will be sorted when the domain is ZZ
  321. ks = []
  322. imax = n//2
  323. if even:
  324. ks.append(imax)
  325. imax -= 1
  326. if not neg:
  327. ks.append(0)
  328. for i in range(imax, 0, -1):
  329. if neg:
  330. ks.extend([i, -i])
  331. else:
  332. ks.extend([-i, i])
  333. if neg:
  334. ks.append(0)
  335. if big:
  336. for i in range(0, len(ks), 2):
  337. pair = ks[i: i + 2]
  338. pair = list(reversed(pair))
  339. # compute the roots
  340. roots, d = [], 2*I*pi/n
  341. for k in ks:
  342. zeta = exp(k*d).expand(complex=True)
  343. roots.append((alpha*zeta).expand(power_base=False))
  344. return roots
  345. def _inv_totient_estimate(m):
  346. """
  347. Find ``(L, U)`` such that ``L <= phi^-1(m) <= U``.
  348. Examples
  349. ========
  350. >>> from sympy.polys.polyroots import _inv_totient_estimate
  351. >>> _inv_totient_estimate(192)
  352. (192, 840)
  353. >>> _inv_totient_estimate(400)
  354. (400, 1750)
  355. """
  356. primes = [ d + 1 for d in divisors(m) if isprime(d + 1) ]
  357. a, b = 1, 1
  358. for p in primes:
  359. a *= p
  360. b *= p - 1
  361. L = m
  362. U = int(math.ceil(m*(float(a)/b)))
  363. P = p = 2
  364. primes = []
  365. while P <= U:
  366. p = nextprime(p)
  367. primes.append(p)
  368. P *= p
  369. P //= p
  370. b = 1
  371. for p in primes[:-1]:
  372. b *= p - 1
  373. U = int(math.ceil(m*(float(P)/b)))
  374. return L, U
  375. def roots_cyclotomic(f, factor=False):
  376. """Compute roots of cyclotomic polynomials. """
  377. L, U = _inv_totient_estimate(f.degree())
  378. for n in range(L, U + 1):
  379. g = cyclotomic_poly(n, f.gen, polys=True)
  380. if f.expr == g.expr:
  381. break
  382. else: # pragma: no cover
  383. raise RuntimeError("failed to find index of a cyclotomic polynomial")
  384. roots = []
  385. if not factor:
  386. # get the indices in the right order so the computed
  387. # roots will be sorted
  388. h = n//2
  389. ks = [i for i in range(1, n + 1) if igcd(i, n) == 1]
  390. ks.sort(key=lambda x: (x, -1) if x <= h else (abs(x - n), 1))
  391. d = 2*I*pi/n
  392. for k in reversed(ks):
  393. roots.append(exp(k*d).expand(complex=True))
  394. else:
  395. g = Poly(f, extension=root(-1, n))
  396. for h, _ in ordered(g.factor_list()[1]):
  397. roots.append(-h.TC())
  398. return roots
  399. def roots_quintic(f):
  400. """
  401. Calculate exact roots of a solvable quintic
  402. """
  403. result = []
  404. coeff_5, coeff_4, p, q, r, s = f.all_coeffs()
  405. # Eqn must be of the form x^5 + px^3 + qx^2 + rx + s
  406. if coeff_4:
  407. return result
  408. if coeff_5 != 1:
  409. l = [p/coeff_5, q/coeff_5, r/coeff_5, s/coeff_5]
  410. if not all(coeff.is_Rational for coeff in l):
  411. return result
  412. f = Poly(f/coeff_5)
  413. elif not all(coeff.is_Rational for coeff in (p, q, r, s)):
  414. return result
  415. quintic = PolyQuintic(f)
  416. # Eqn standardized. Algo for solving starts here
  417. if not f.is_irreducible:
  418. return result
  419. f20 = quintic.f20
  420. # Check if f20 has linear factors over domain Z
  421. if f20.is_irreducible:
  422. return result
  423. # Now, we know that f is solvable
  424. for _factor in f20.factor_list()[1]:
  425. if _factor[0].is_linear:
  426. theta = _factor[0].root(0)
  427. break
  428. d = discriminant(f)
  429. delta = sqrt(d)
  430. # zeta = a fifth root of unity
  431. zeta1, zeta2, zeta3, zeta4 = quintic.zeta
  432. T = quintic.T(theta, d)
  433. tol = S(1e-10)
  434. alpha = T[1] + T[2]*delta
  435. alpha_bar = T[1] - T[2]*delta
  436. beta = T[3] + T[4]*delta
  437. beta_bar = T[3] - T[4]*delta
  438. disc = alpha**2 - 4*beta
  439. disc_bar = alpha_bar**2 - 4*beta_bar
  440. l0 = quintic.l0(theta)
  441. Stwo = S(2)
  442. l1 = _quintic_simplify((-alpha + sqrt(disc)) / Stwo)
  443. l4 = _quintic_simplify((-alpha - sqrt(disc)) / Stwo)
  444. l2 = _quintic_simplify((-alpha_bar + sqrt(disc_bar)) / Stwo)
  445. l3 = _quintic_simplify((-alpha_bar - sqrt(disc_bar)) / Stwo)
  446. order = quintic.order(theta, d)
  447. test = (order*delta.n()) - ( (l1.n() - l4.n())*(l2.n() - l3.n()) )
  448. # Comparing floats
  449. if not comp(test, 0, tol):
  450. l2, l3 = l3, l2
  451. # Now we have correct order of l's
  452. R1 = l0 + l1*zeta1 + l2*zeta2 + l3*zeta3 + l4*zeta4
  453. R2 = l0 + l3*zeta1 + l1*zeta2 + l4*zeta3 + l2*zeta4
  454. R3 = l0 + l2*zeta1 + l4*zeta2 + l1*zeta3 + l3*zeta4
  455. R4 = l0 + l4*zeta1 + l3*zeta2 + l2*zeta3 + l1*zeta4
  456. Res = [None, [None]*5, [None]*5, [None]*5, [None]*5]
  457. Res_n = [None, [None]*5, [None]*5, [None]*5, [None]*5]
  458. sol = Symbol('sol')
  459. # Simplifying improves performance a lot for exact expressions
  460. R1 = _quintic_simplify(R1)
  461. R2 = _quintic_simplify(R2)
  462. R3 = _quintic_simplify(R3)
  463. R4 = _quintic_simplify(R4)
  464. # Solve imported here. Causing problems if imported as 'solve'
  465. # and hence the changed name
  466. from sympy.solvers.solvers import solve as _solve
  467. a, b = symbols('a b', cls=Dummy)
  468. _sol = _solve( sol**5 - a - I*b, sol)
  469. for i in range(5):
  470. _sol[i] = factor(_sol[i])
  471. R1 = R1.as_real_imag()
  472. R2 = R2.as_real_imag()
  473. R3 = R3.as_real_imag()
  474. R4 = R4.as_real_imag()
  475. for i, currentroot in enumerate(_sol):
  476. Res[1][i] = _quintic_simplify(currentroot.subs({ a: R1[0], b: R1[1] }))
  477. Res[2][i] = _quintic_simplify(currentroot.subs({ a: R2[0], b: R2[1] }))
  478. Res[3][i] = _quintic_simplify(currentroot.subs({ a: R3[0], b: R3[1] }))
  479. Res[4][i] = _quintic_simplify(currentroot.subs({ a: R4[0], b: R4[1] }))
  480. for i in range(1, 5):
  481. for j in range(5):
  482. Res_n[i][j] = Res[i][j].n()
  483. Res[i][j] = _quintic_simplify(Res[i][j])
  484. r1 = Res[1][0]
  485. r1_n = Res_n[1][0]
  486. for i in range(5):
  487. if comp(im(r1_n*Res_n[4][i]), 0, tol):
  488. r4 = Res[4][i]
  489. break
  490. # Now we have various Res values. Each will be a list of five
  491. # values. We have to pick one r value from those five for each Res
  492. u, v = quintic.uv(theta, d)
  493. testplus = (u + v*delta*sqrt(5)).n()
  494. testminus = (u - v*delta*sqrt(5)).n()
  495. # Evaluated numbers suffixed with _n
  496. # We will use evaluated numbers for calculation. Much faster.
  497. r4_n = r4.n()
  498. r2 = r3 = None
  499. for i in range(5):
  500. r2temp_n = Res_n[2][i]
  501. for j in range(5):
  502. # Again storing away the exact number and using
  503. # evaluated numbers in computations
  504. r3temp_n = Res_n[3][j]
  505. if (comp((r1_n*r2temp_n**2 + r4_n*r3temp_n**2 - testplus).n(), 0, tol) and
  506. comp((r3temp_n*r1_n**2 + r2temp_n*r4_n**2 - testminus).n(), 0, tol)):
  507. r2 = Res[2][i]
  508. r3 = Res[3][j]
  509. break
  510. if r2:
  511. break
  512. else:
  513. return [] # fall back to normal solve
  514. # Now, we have r's so we can get roots
  515. x1 = (r1 + r2 + r3 + r4)/5
  516. x2 = (r1*zeta4 + r2*zeta3 + r3*zeta2 + r4*zeta1)/5
  517. x3 = (r1*zeta3 + r2*zeta1 + r3*zeta4 + r4*zeta2)/5
  518. x4 = (r1*zeta2 + r2*zeta4 + r3*zeta1 + r4*zeta3)/5
  519. x5 = (r1*zeta1 + r2*zeta2 + r3*zeta3 + r4*zeta4)/5
  520. result = [x1, x2, x3, x4, x5]
  521. # Now check if solutions are distinct
  522. saw = set()
  523. for r in result:
  524. r = r.n(2)
  525. if r in saw:
  526. # Roots were identical. Abort, return []
  527. # and fall back to usual solve
  528. return []
  529. saw.add(r)
  530. return result
  531. def _quintic_simplify(expr):
  532. expr = powsimp(expr)
  533. expr = cancel(expr)
  534. return together(expr)
  535. def _integer_basis(poly):
  536. """Compute coefficient basis for a polynomial over integers.
  537. Returns the integer ``div`` such that substituting ``x = div*y``
  538. ``p(x) = m*q(y)`` where the coefficients of ``q`` are smaller
  539. than those of ``p``.
  540. For example ``x**5 + 512*x + 1024 = 0``
  541. with ``div = 4`` becomes ``y**5 + 2*y + 1 = 0``
  542. Returns the integer ``div`` or ``None`` if there is no possible scaling.
  543. Examples
  544. ========
  545. >>> from sympy.polys import Poly
  546. >>> from sympy.abc import x
  547. >>> from sympy.polys.polyroots import _integer_basis
  548. >>> p = Poly(x**5 + 512*x + 1024, x, domain='ZZ')
  549. >>> _integer_basis(p)
  550. 4
  551. """
  552. monoms, coeffs = list(zip(*poly.terms()))
  553. monoms, = list(zip(*monoms))
  554. coeffs = list(map(abs, coeffs))
  555. if coeffs[0] < coeffs[-1]:
  556. coeffs = list(reversed(coeffs))
  557. n = monoms[0]
  558. monoms = [n - i for i in reversed(monoms)]
  559. else:
  560. return None
  561. monoms = monoms[:-1]
  562. coeffs = coeffs[:-1]
  563. # Special case for two-term polynominals
  564. if len(monoms) == 1:
  565. r = Pow(coeffs[0], S.One/monoms[0])
  566. if r.is_Integer:
  567. return int(r)
  568. else:
  569. return None
  570. divs = reversed(divisors(gcd_list(coeffs))[1:])
  571. try:
  572. div = next(divs)
  573. except StopIteration:
  574. return None
  575. while True:
  576. for monom, coeff in zip(monoms, coeffs):
  577. if coeff % div**monom != 0:
  578. try:
  579. div = next(divs)
  580. except StopIteration:
  581. return None
  582. else:
  583. break
  584. else:
  585. return div
  586. def preprocess_roots(poly):
  587. """Try to get rid of symbolic coefficients from ``poly``. """
  588. coeff = S.One
  589. poly_func = poly.func
  590. try:
  591. _, poly = poly.clear_denoms(convert=True)
  592. except DomainError:
  593. return coeff, poly
  594. poly = poly.primitive()[1]
  595. poly = poly.retract()
  596. # TODO: This is fragile. Figure out how to make this independent of construct_domain().
  597. if poly.get_domain().is_Poly and all(c.is_term for c in poly.rep.coeffs()):
  598. poly = poly.inject()
  599. strips = list(zip(*poly.monoms()))
  600. gens = list(poly.gens[1:])
  601. base, strips = strips[0], strips[1:]
  602. for gen, strip in zip(list(gens), strips):
  603. reverse = False
  604. if strip[0] < strip[-1]:
  605. strip = reversed(strip)
  606. reverse = True
  607. ratio = None
  608. for a, b in zip(base, strip):
  609. if not a and not b:
  610. continue
  611. elif not a or not b:
  612. break
  613. elif b % a != 0:
  614. break
  615. else:
  616. _ratio = b // a
  617. if ratio is None:
  618. ratio = _ratio
  619. elif ratio != _ratio:
  620. break
  621. else:
  622. if reverse:
  623. ratio = -ratio
  624. poly = poly.eval(gen, 1)
  625. coeff *= gen**(-ratio)
  626. gens.remove(gen)
  627. if gens:
  628. poly = poly.eject(*gens)
  629. if poly.is_univariate and poly.get_domain().is_ZZ:
  630. basis = _integer_basis(poly)
  631. if basis is not None:
  632. n = poly.degree()
  633. def func(k, coeff):
  634. return coeff//basis**(n - k[0])
  635. poly = poly.termwise(func)
  636. coeff *= basis
  637. if not isinstance(poly, poly_func):
  638. poly = poly_func(poly)
  639. return coeff, poly
  640. @public
  641. def roots(f, *gens,
  642. auto=True,
  643. cubics=True,
  644. trig=False,
  645. quartics=True,
  646. quintics=False,
  647. multiple=False,
  648. filter=None,
  649. predicate=None,
  650. **flags):
  651. """
  652. Computes symbolic roots of a univariate polynomial.
  653. Given a univariate polynomial f with symbolic coefficients (or
  654. a list of the polynomial's coefficients), returns a dictionary
  655. with its roots and their multiplicities.
  656. Only roots expressible via radicals will be returned. To get
  657. a complete set of roots use RootOf class or numerical methods
  658. instead. By default cubic and quartic formulas are used in
  659. the algorithm. To disable them because of unreadable output
  660. set ``cubics=False`` or ``quartics=False`` respectively. If cubic
  661. roots are real but are expressed in terms of complex numbers
  662. (casus irreducibilis [1]) the ``trig`` flag can be set to True to
  663. have the solutions returned in terms of cosine and inverse cosine
  664. functions.
  665. To get roots from a specific domain set the ``filter`` flag with
  666. one of the following specifiers: Z, Q, R, I, C. By default all
  667. roots are returned (this is equivalent to setting ``filter='C'``).
  668. By default a dictionary is returned giving a compact result in
  669. case of multiple roots. However to get a list containing all
  670. those roots set the ``multiple`` flag to True; the list will
  671. have identical roots appearing next to each other in the result.
  672. (For a given Poly, the all_roots method will give the roots in
  673. sorted numerical order.)
  674. Examples
  675. ========
  676. >>> from sympy import Poly, roots
  677. >>> from sympy.abc import x, y
  678. >>> roots(x**2 - 1, x)
  679. {-1: 1, 1: 1}
  680. >>> p = Poly(x**2-1, x)
  681. >>> roots(p)
  682. {-1: 1, 1: 1}
  683. >>> p = Poly(x**2-y, x, y)
  684. >>> roots(Poly(p, x))
  685. {-sqrt(y): 1, sqrt(y): 1}
  686. >>> roots(x**2 - y, x)
  687. {-sqrt(y): 1, sqrt(y): 1}
  688. >>> roots([1, 0, -1])
  689. {-1: 1, 1: 1}
  690. References
  691. ==========
  692. .. [1] https://en.wikipedia.org/wiki/Cubic_function#Trigonometric_.28and_hyperbolic.29_method
  693. """
  694. from sympy.polys.polytools import to_rational_coeffs
  695. flags = dict(flags)
  696. if isinstance(f, list):
  697. if gens:
  698. raise ValueError('redundant generators given')
  699. x = Dummy('x')
  700. poly, i = {}, len(f) - 1
  701. for coeff in f:
  702. poly[i], i = sympify(coeff), i - 1
  703. f = Poly(poly, x, field=True)
  704. else:
  705. try:
  706. F = Poly(f, *gens, **flags)
  707. if not isinstance(f, Poly) and not F.gen.is_Symbol:
  708. raise PolynomialError("generator must be a Symbol")
  709. else:
  710. f = F
  711. if f.length == 2 and f.degree() != 1:
  712. # check for foo**n factors in the constant
  713. n = f.degree()
  714. npow_bases = []
  715. others = []
  716. expr = f.as_expr()
  717. con = expr.as_independent(*gens)[0]
  718. for p in Mul.make_args(con):
  719. if p.is_Pow and not p.exp % n:
  720. npow_bases.append(p.base**(p.exp/n))
  721. else:
  722. others.append(p)
  723. if npow_bases:
  724. b = Mul(*npow_bases)
  725. B = Dummy()
  726. d = roots(Poly(expr - con + B**n*Mul(*others), *gens,
  727. **flags), *gens, **flags)
  728. rv = {}
  729. for k, v in d.items():
  730. rv[k.subs(B, b)] = v
  731. return rv
  732. except GeneratorsNeeded:
  733. if multiple:
  734. return []
  735. else:
  736. return {}
  737. if f.is_multivariate:
  738. raise PolynomialError('multivariate polynomials are not supported')
  739. def _update_dict(result, zeros, currentroot, k):
  740. if currentroot == S.Zero:
  741. if S.Zero in zeros:
  742. zeros[S.Zero] += k
  743. else:
  744. zeros[S.Zero] = k
  745. if currentroot in result:
  746. result[currentroot] += k
  747. else:
  748. result[currentroot] = k
  749. def _try_decompose(f):
  750. """Find roots using functional decomposition. """
  751. factors, roots = f.decompose(), []
  752. for currentroot in _try_heuristics(factors[0]):
  753. roots.append(currentroot)
  754. for currentfactor in factors[1:]:
  755. previous, roots = list(roots), []
  756. for currentroot in previous:
  757. g = currentfactor - Poly(currentroot, f.gen)
  758. for currentroot in _try_heuristics(g):
  759. roots.append(currentroot)
  760. return roots
  761. def _try_heuristics(f):
  762. """Find roots using formulas and some tricks. """
  763. if f.is_ground:
  764. return []
  765. if f.is_monomial:
  766. return [S.Zero]*f.degree()
  767. if f.length() == 2:
  768. if f.degree() == 1:
  769. return list(map(cancel, roots_linear(f)))
  770. else:
  771. return roots_binomial(f)
  772. result = []
  773. for i in [-1, 1]:
  774. if not f.eval(i):
  775. f = f.quo(Poly(f.gen - i, f.gen))
  776. result.append(i)
  777. break
  778. n = f.degree()
  779. if n == 1:
  780. result += list(map(cancel, roots_linear(f)))
  781. elif n == 2:
  782. result += list(map(cancel, roots_quadratic(f)))
  783. elif f.is_cyclotomic:
  784. result += roots_cyclotomic(f)
  785. elif n == 3 and cubics:
  786. result += roots_cubic(f, trig=trig)
  787. elif n == 4 and quartics:
  788. result += roots_quartic(f)
  789. elif n == 5 and quintics:
  790. result += roots_quintic(f)
  791. return result
  792. # Convert the generators to symbols
  793. dumgens = symbols('x:%d' % len(f.gens), cls=Dummy)
  794. f = f.per(f.rep, dumgens)
  795. (k,), f = f.terms_gcd()
  796. if not k:
  797. zeros = {}
  798. else:
  799. zeros = {S.Zero: k}
  800. coeff, f = preprocess_roots(f)
  801. if auto and f.get_domain().is_Ring:
  802. f = f.to_field()
  803. # Use EX instead of ZZ_I or QQ_I
  804. if f.get_domain().is_QQ_I:
  805. f = f.per(f.rep.convert(EX))
  806. rescale_x = None
  807. translate_x = None
  808. result = {}
  809. if not f.is_ground:
  810. dom = f.get_domain()
  811. if not dom.is_Exact and dom.is_Numerical:
  812. for r in f.nroots():
  813. _update_dict(result, zeros, r, 1)
  814. elif f.degree() == 1:
  815. _update_dict(result, zeros, roots_linear(f)[0], 1)
  816. elif f.length() == 2:
  817. roots_fun = roots_quadratic if f.degree() == 2 else roots_binomial
  818. for r in roots_fun(f):
  819. _update_dict(result, zeros, r, 1)
  820. else:
  821. _, factors = Poly(f.as_expr()).factor_list()
  822. if len(factors) == 1 and f.degree() == 2:
  823. for r in roots_quadratic(f):
  824. _update_dict(result, zeros, r, 1)
  825. else:
  826. if len(factors) == 1 and factors[0][1] == 1:
  827. if f.get_domain().is_EX:
  828. res = to_rational_coeffs(f)
  829. if res:
  830. if res[0] is None:
  831. translate_x, f = res[2:]
  832. else:
  833. rescale_x, f = res[1], res[-1]
  834. result = roots(f)
  835. if not result:
  836. for currentroot in _try_decompose(f):
  837. _update_dict(result, zeros, currentroot, 1)
  838. else:
  839. for r in _try_heuristics(f):
  840. _update_dict(result, zeros, r, 1)
  841. else:
  842. for currentroot in _try_decompose(f):
  843. _update_dict(result, zeros, currentroot, 1)
  844. else:
  845. for currentfactor, k in factors:
  846. for r in _try_heuristics(Poly(currentfactor, f.gen, field=True)):
  847. _update_dict(result, zeros, r, k)
  848. if coeff is not S.One:
  849. _result, result, = result, {}
  850. for currentroot, k in _result.items():
  851. result[coeff*currentroot] = k
  852. if filter not in [None, 'C']:
  853. handlers = {
  854. 'Z': lambda r: r.is_Integer,
  855. 'Q': lambda r: r.is_Rational,
  856. 'R': lambda r: all(a.is_real for a in r.as_numer_denom()),
  857. 'I': lambda r: r.is_imaginary,
  858. }
  859. try:
  860. query = handlers[filter]
  861. except KeyError:
  862. raise ValueError("Invalid filter: %s" % filter)
  863. for zero in dict(result).keys():
  864. if not query(zero):
  865. del result[zero]
  866. if predicate is not None:
  867. for zero in dict(result).keys():
  868. if not predicate(zero):
  869. del result[zero]
  870. if rescale_x:
  871. result1 = {}
  872. for k, v in result.items():
  873. result1[k*rescale_x] = v
  874. result = result1
  875. if translate_x:
  876. result1 = {}
  877. for k, v in result.items():
  878. result1[k + translate_x] = v
  879. result = result1
  880. # adding zero roots after non-trivial roots have been translated
  881. result.update(zeros)
  882. if not multiple:
  883. return result
  884. else:
  885. zeros = []
  886. for zero in ordered(result):
  887. zeros.extend([zero]*result[zero])
  888. return zeros
  889. def root_factors(f, *gens, filter=None, **args):
  890. """
  891. Returns all factors of a univariate polynomial.
  892. Examples
  893. ========
  894. >>> from sympy.abc import x, y
  895. >>> from sympy.polys.polyroots import root_factors
  896. >>> root_factors(x**2 - y, x)
  897. [x - sqrt(y), x + sqrt(y)]
  898. """
  899. args = dict(args)
  900. F = Poly(f, *gens, **args)
  901. if not F.is_Poly:
  902. return [f]
  903. if F.is_multivariate:
  904. raise ValueError('multivariate polynomials are not supported')
  905. x = F.gens[0]
  906. zeros = roots(F, filter=filter)
  907. if not zeros:
  908. factors = [F]
  909. else:
  910. factors, N = [], 0
  911. for r, n in ordered(zeros.items()):
  912. factors, N = factors + [Poly(x - r, x)]*n, N + n
  913. if N < F.degree():
  914. G = reduce(lambda p, q: p*q, factors)
  915. factors.append(F.quo(G))
  916. if not isinstance(f, Poly):
  917. factors = [ f.as_expr() for f in factors ]
  918. return factors