minpoly.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. """Minimal polynomials for algebraic numbers."""
  2. from functools import reduce
  3. from sympy.core.add import Add
  4. from sympy.core.exprtools import Factors
  5. from sympy.core.function import expand_mul, expand_multinomial, _mexpand
  6. from sympy.core.mul import Mul
  7. from sympy.core.numbers import (I, Rational, pi, _illegal)
  8. from sympy.core.singleton import S
  9. from sympy.core.symbol import Dummy
  10. from sympy.core.sympify import sympify
  11. from sympy.core.traversal import preorder_traversal
  12. from sympy.functions.elementary.exponential import exp
  13. from sympy.functions.elementary.miscellaneous import sqrt, cbrt
  14. from sympy.functions.elementary.trigonometric import cos, sin, tan
  15. from sympy.ntheory.factor_ import divisors
  16. from sympy.utilities.iterables import subsets
  17. from sympy.polys.domains import ZZ, QQ, FractionField
  18. from sympy.polys.orthopolys import dup_chebyshevt
  19. from sympy.polys.polyerrors import (
  20. NotAlgebraic,
  21. GeneratorsError,
  22. )
  23. from sympy.polys.polytools import (
  24. Poly, PurePoly, invert, factor_list, groebner, resultant,
  25. degree, poly_from_expr, parallel_poly_from_expr, lcm
  26. )
  27. from sympy.polys.polyutils import dict_from_expr, expr_from_dict
  28. from sympy.polys.ring_series import rs_compose_add
  29. from sympy.polys.rings import ring
  30. from sympy.polys.rootoftools import CRootOf
  31. from sympy.polys.specialpolys import cyclotomic_poly
  32. from sympy.utilities import (
  33. numbered_symbols, public, sift
  34. )
  35. def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5):
  36. """
  37. Return a factor having root ``v``
  38. It is assumed that one of the factors has root ``v``.
  39. """
  40. if isinstance(factors[0], tuple):
  41. factors = [f[0] for f in factors]
  42. if len(factors) == 1:
  43. return factors[0]
  44. prec1 = 10
  45. points = {}
  46. symbols = dom.symbols if hasattr(dom, 'symbols') else []
  47. while prec1 <= prec:
  48. # when dealing with non-Rational numbers we usually evaluate
  49. # with `subs` argument but we only need a ballpark evaluation
  50. fe = [f.as_expr().xreplace({x:v}) for f in factors]
  51. if v.is_number:
  52. fe = [f.n(prec) for f in fe]
  53. # assign integers [0, n) to symbols (if any)
  54. for n in subsets(range(bound), k=len(symbols), repetition=True):
  55. for s, i in zip(symbols, n):
  56. points[s] = i
  57. # evaluate the expression at these points
  58. candidates = [(abs(f.subs(points).n(prec1)), i)
  59. for i,f in enumerate(fe)]
  60. # if we get invalid numbers (e.g. from division by zero)
  61. # we try again
  62. if any(i in _illegal for i, _ in candidates):
  63. continue
  64. # find the smallest two -- if they differ significantly
  65. # then we assume we have found the factor that becomes
  66. # 0 when v is substituted into it
  67. can = sorted(candidates)
  68. (a, ix), (b, _) = can[:2]
  69. if b > a * 10**6: # XXX what to use?
  70. return factors[ix]
  71. prec1 *= 2
  72. raise NotImplementedError("multiple candidates for the minimal polynomial of %s" % v)
  73. def _is_sum_surds(p):
  74. args = p.args if p.is_Add else [p]
  75. for y in args:
  76. if not ((y**2).is_Rational and y.is_extended_real):
  77. return False
  78. return True
  79. def _separate_sq(p):
  80. """
  81. helper function for ``_minimal_polynomial_sq``
  82. It selects a rational ``g`` such that the polynomial ``p``
  83. consists of a sum of terms whose surds squared have gcd equal to ``g``
  84. and a sum of terms with surds squared prime with ``g``;
  85. then it takes the field norm to eliminate ``sqrt(g)``
  86. See simplify.simplify.split_surds and polytools.sqf_norm.
  87. Examples
  88. ========
  89. >>> from sympy import sqrt
  90. >>> from sympy.abc import x
  91. >>> from sympy.polys.numberfields.minpoly import _separate_sq
  92. >>> p= -x + sqrt(2) + sqrt(3) + sqrt(7)
  93. >>> p = _separate_sq(p); p
  94. -x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8
  95. >>> p = _separate_sq(p); p
  96. -x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20
  97. >>> p = _separate_sq(p); p
  98. -x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400
  99. """
  100. def is_sqrt(expr):
  101. return expr.is_Pow and expr.exp is S.Half
  102. # p = c1*sqrt(q1) + ... + cn*sqrt(qn) -> a = [(c1, q1), .., (cn, qn)]
  103. a = []
  104. for y in p.args:
  105. if not y.is_Mul:
  106. if is_sqrt(y):
  107. a.append((S.One, y**2))
  108. elif y.is_Atom:
  109. a.append((y, S.One))
  110. elif y.is_Pow and y.exp.is_integer:
  111. a.append((y, S.One))
  112. else:
  113. raise NotImplementedError
  114. else:
  115. T, F = sift(y.args, is_sqrt, binary=True)
  116. a.append((Mul(*F), Mul(*T)**2))
  117. a.sort(key=lambda z: z[1])
  118. if a[-1][1] is S.One:
  119. # there are no surds
  120. return p
  121. surds = [z for y, z in a]
  122. for i in range(len(surds)):
  123. if surds[i] != 1:
  124. break
  125. from sympy.simplify.radsimp import _split_gcd
  126. g, b1, b2 = _split_gcd(*surds[i:])
  127. a1 = []
  128. a2 = []
  129. for y, z in a:
  130. if z in b1:
  131. a1.append(y*z**S.Half)
  132. else:
  133. a2.append(y*z**S.Half)
  134. p1 = Add(*a1)
  135. p2 = Add(*a2)
  136. p = _mexpand(p1**2) - _mexpand(p2**2)
  137. return p
  138. def _minimal_polynomial_sq(p, n, x):
  139. """
  140. Returns the minimal polynomial for the ``nth-root`` of a sum of surds
  141. or ``None`` if it fails.
  142. Parameters
  143. ==========
  144. p : sum of surds
  145. n : positive integer
  146. x : variable of the returned polynomial
  147. Examples
  148. ========
  149. >>> from sympy.polys.numberfields.minpoly import _minimal_polynomial_sq
  150. >>> from sympy import sqrt
  151. >>> from sympy.abc import x
  152. >>> q = 1 + sqrt(2) + sqrt(3)
  153. >>> _minimal_polynomial_sq(q, 3, x)
  154. x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8
  155. """
  156. p = sympify(p)
  157. n = sympify(n)
  158. if not n.is_Integer or not n > 0 or not _is_sum_surds(p):
  159. return None
  160. pn = p**Rational(1, n)
  161. # eliminate the square roots
  162. p -= x
  163. while 1:
  164. p1 = _separate_sq(p)
  165. if p1 is p:
  166. p = p1.subs({x:x**n})
  167. break
  168. else:
  169. p = p1
  170. # _separate_sq eliminates field extensions in a minimal way, so that
  171. # if n = 1 then `p = constant*(minimal_polynomial(p))`
  172. # if n > 1 it contains the minimal polynomial as a factor.
  173. if n == 1:
  174. p1 = Poly(p)
  175. if p.coeff(x**p1.degree(x)) < 0:
  176. p = -p
  177. p = p.primitive()[1]
  178. return p
  179. # by construction `p` has root `pn`
  180. # the minimal polynomial is the factor vanishing in x = pn
  181. factors = factor_list(p)[1]
  182. result = _choose_factor(factors, x, pn)
  183. return result
  184. def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None):
  185. """
  186. return the minimal polynomial for ``op(ex1, ex2)``
  187. Parameters
  188. ==========
  189. op : operation ``Add`` or ``Mul``
  190. ex1, ex2 : expressions for the algebraic elements
  191. x : indeterminate of the polynomials
  192. dom: ground domain
  193. mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None
  194. Examples
  195. ========
  196. >>> from sympy import sqrt, Add, Mul, QQ
  197. >>> from sympy.polys.numberfields.minpoly import _minpoly_op_algebraic_element
  198. >>> from sympy.abc import x, y
  199. >>> p1 = sqrt(sqrt(2) + 1)
  200. >>> p2 = sqrt(sqrt(2) - 1)
  201. >>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ)
  202. x - 1
  203. >>> q1 = sqrt(y)
  204. >>> q2 = 1 / y
  205. >>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y))
  206. x**2*y**2 - 2*x*y - y**3 + 1
  207. References
  208. ==========
  209. .. [1] https://en.wikipedia.org/wiki/Resultant
  210. .. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638
  211. "Degrees of sums in a separable field extension".
  212. """
  213. y = Dummy(str(x))
  214. if mp1 is None:
  215. mp1 = _minpoly_compose(ex1, x, dom)
  216. if mp2 is None:
  217. mp2 = _minpoly_compose(ex2, y, dom)
  218. else:
  219. mp2 = mp2.subs({x: y})
  220. if op is Add:
  221. # mp1a = mp1.subs({x: x - y})
  222. if dom == QQ:
  223. R, X = ring('X', QQ)
  224. p1 = R(dict_from_expr(mp1)[0])
  225. p2 = R(dict_from_expr(mp2)[0])
  226. else:
  227. (p1, p2), _ = parallel_poly_from_expr((mp1, x - y), x, y)
  228. r = p1.compose(p2)
  229. mp1a = r.as_expr()
  230. elif op is Mul:
  231. mp1a = _muly(mp1, x, y)
  232. else:
  233. raise NotImplementedError('option not available')
  234. if op is Mul or dom != QQ:
  235. r = resultant(mp1a, mp2, gens=[y, x])
  236. else:
  237. r = rs_compose_add(p1, p2)
  238. r = expr_from_dict(r.as_expr_dict(), x)
  239. deg1 = degree(mp1, x)
  240. deg2 = degree(mp2, y)
  241. if op is Mul and deg1 == 1 or deg2 == 1:
  242. # if deg1 = 1, then mp1 = x - a; mp1a = x - y - a;
  243. # r = mp2(x - a), so that `r` is irreducible
  244. return r
  245. r = Poly(r, x, domain=dom)
  246. _, factors = r.factor_list()
  247. res = _choose_factor(factors, x, op(ex1, ex2), dom)
  248. return res.as_expr()
  249. def _invertx(p, x):
  250. """
  251. Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))``
  252. """
  253. p1 = poly_from_expr(p, x)[0]
  254. n = degree(p1)
  255. a = [c * x**(n - i) for (i,), c in p1.terms()]
  256. return Add(*a)
  257. def _muly(p, x, y):
  258. """
  259. Returns ``_mexpand(y**deg*p.subs({x:x / y}))``
  260. """
  261. p1 = poly_from_expr(p, x)[0]
  262. n = degree(p1)
  263. a = [c * x**i * y**(n - i) for (i,), c in p1.terms()]
  264. return Add(*a)
  265. def _minpoly_pow(ex, pw, x, dom, mp=None):
  266. """
  267. Returns ``minpoly(ex**pw, x)``
  268. Parameters
  269. ==========
  270. ex : algebraic element
  271. pw : rational number
  272. x : indeterminate of the polynomial
  273. dom: ground domain
  274. mp : minimal polynomial of ``p``
  275. Examples
  276. ========
  277. >>> from sympy import sqrt, QQ, Rational
  278. >>> from sympy.polys.numberfields.minpoly import _minpoly_pow, minpoly
  279. >>> from sympy.abc import x, y
  280. >>> p = sqrt(1 + sqrt(2))
  281. >>> _minpoly_pow(p, 2, x, QQ)
  282. x**2 - 2*x - 1
  283. >>> minpoly(p**2, x)
  284. x**2 - 2*x - 1
  285. >>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y))
  286. x**3 - y
  287. >>> minpoly(y**Rational(1, 3), x)
  288. x**3 - y
  289. """
  290. pw = sympify(pw)
  291. if not mp:
  292. mp = _minpoly_compose(ex, x, dom)
  293. if not pw.is_rational:
  294. raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
  295. if pw < 0:
  296. if mp == x:
  297. raise ZeroDivisionError('%s is zero' % ex)
  298. mp = _invertx(mp, x)
  299. if pw == -1:
  300. return mp
  301. pw = -pw
  302. ex = 1/ex
  303. y = Dummy(str(x))
  304. mp = mp.subs({x: y})
  305. n, d = pw.as_numer_denom()
  306. res = Poly(resultant(mp, x**d - y**n, gens=[y]), x, domain=dom)
  307. _, factors = res.factor_list()
  308. res = _choose_factor(factors, x, ex**pw, dom)
  309. return res.as_expr()
  310. def _minpoly_add(x, dom, *a):
  311. """
  312. returns ``minpoly(Add(*a), dom, x)``
  313. """
  314. mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom)
  315. p = a[0] + a[1]
  316. for px in a[2:]:
  317. mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp)
  318. p = p + px
  319. return mp
  320. def _minpoly_mul(x, dom, *a):
  321. """
  322. returns ``minpoly(Mul(*a), dom, x)``
  323. """
  324. mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom)
  325. p = a[0] * a[1]
  326. for px in a[2:]:
  327. mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp)
  328. p = p * px
  329. return mp
  330. def _minpoly_sin(ex, x):
  331. """
  332. Returns the minimal polynomial of ``sin(ex)``
  333. see https://mathworld.wolfram.com/TrigonometryAngles.html
  334. """
  335. c, a = ex.args[0].as_coeff_Mul()
  336. if a is pi:
  337. if c.is_rational:
  338. n = c.q
  339. q = sympify(n)
  340. if q.is_prime:
  341. # for a = pi*p/q with q odd prime, using chebyshevt
  342. # write sin(q*a) = mp(sin(a))*sin(a);
  343. # the roots of mp(x) are sin(pi*p/q) for p = 1,..., q - 1
  344. a = dup_chebyshevt(n, ZZ)
  345. return Add(*[x**(n - i - 1)*a[i] for i in range(n)])
  346. if c.p == 1:
  347. if q == 9:
  348. return 64*x**6 - 96*x**4 + 36*x**2 - 3
  349. if n % 2 == 1:
  350. # for a = pi*p/q with q odd, use
  351. # sin(q*a) = 0 to see that the minimal polynomial must be
  352. # a factor of dup_chebyshevt(n, ZZ)
  353. a = dup_chebyshevt(n, ZZ)
  354. a = [x**(n - i)*a[i] for i in range(n + 1)]
  355. r = Add(*a)
  356. _, factors = factor_list(r)
  357. res = _choose_factor(factors, x, ex)
  358. return res
  359. expr = ((1 - cos(2*c*pi))/2)**S.Half
  360. res = _minpoly_compose(expr, x, QQ)
  361. return res
  362. raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
  363. def _minpoly_cos(ex, x):
  364. """
  365. Returns the minimal polynomial of ``cos(ex)``
  366. see https://mathworld.wolfram.com/TrigonometryAngles.html
  367. """
  368. c, a = ex.args[0].as_coeff_Mul()
  369. if a is pi:
  370. if c.is_rational:
  371. if c.p == 1:
  372. if c.q == 7:
  373. return 8*x**3 - 4*x**2 - 4*x + 1
  374. if c.q == 9:
  375. return 8*x**3 - 6*x - 1
  376. elif c.p == 2:
  377. q = sympify(c.q)
  378. if q.is_prime:
  379. s = _minpoly_sin(ex, x)
  380. return _mexpand(s.subs({x:sqrt((1 - x)/2)}))
  381. # for a = pi*p/q, cos(q*a) =T_q(cos(a)) = (-1)**p
  382. n = int(c.q)
  383. a = dup_chebyshevt(n, ZZ)
  384. a = [x**(n - i)*a[i] for i in range(n + 1)]
  385. r = Add(*a) - (-1)**c.p
  386. _, factors = factor_list(r)
  387. res = _choose_factor(factors, x, ex)
  388. return res
  389. raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
  390. def _minpoly_tan(ex, x):
  391. """
  392. Returns the minimal polynomial of ``tan(ex)``
  393. see https://github.com/sympy/sympy/issues/21430
  394. """
  395. c, a = ex.args[0].as_coeff_Mul()
  396. if a is pi:
  397. if c.is_rational:
  398. c = c * 2
  399. n = int(c.q)
  400. a = n if c.p % 2 == 0 else 1
  401. terms = []
  402. for k in range((c.p+1)%2, n+1, 2):
  403. terms.append(a*x**k)
  404. a = -(a*(n-k-1)*(n-k)) // ((k+1)*(k+2))
  405. r = Add(*terms)
  406. _, factors = factor_list(r)
  407. res = _choose_factor(factors, x, ex)
  408. return res
  409. raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
  410. def _minpoly_exp(ex, x):
  411. """
  412. Returns the minimal polynomial of ``exp(ex)``
  413. """
  414. c, a = ex.args[0].as_coeff_Mul()
  415. if a == I*pi:
  416. if c.is_rational:
  417. q = sympify(c.q)
  418. if c.p == 1 or c.p == -1:
  419. if q == 3:
  420. return x**2 - x + 1
  421. if q == 4:
  422. return x**4 + 1
  423. if q == 6:
  424. return x**4 - x**2 + 1
  425. if q == 8:
  426. return x**8 + 1
  427. if q == 9:
  428. return x**6 - x**3 + 1
  429. if q == 10:
  430. return x**8 - x**6 + x**4 - x**2 + 1
  431. if q.is_prime:
  432. s = 0
  433. for i in range(q):
  434. s += (-x)**i
  435. return s
  436. # x**(2*q) = product(factors)
  437. factors = [cyclotomic_poly(i, x) for i in divisors(2*q)]
  438. mp = _choose_factor(factors, x, ex)
  439. return mp
  440. else:
  441. raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
  442. raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
  443. def _minpoly_rootof(ex, x):
  444. """
  445. Returns the minimal polynomial of a ``CRootOf`` object.
  446. """
  447. p = ex.expr
  448. p = p.subs({ex.poly.gens[0]:x})
  449. _, factors = factor_list(p, x)
  450. result = _choose_factor(factors, x, ex)
  451. return result
  452. def _minpoly_compose(ex, x, dom):
  453. """
  454. Computes the minimal polynomial of an algebraic element
  455. using operations on minimal polynomials
  456. Examples
  457. ========
  458. >>> from sympy import minimal_polynomial, sqrt, Rational
  459. >>> from sympy.abc import x, y
  460. >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True)
  461. x**2 - 2*x - 1
  462. >>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True)
  463. x**2*y**2 - 2*x*y - y**3 + 1
  464. """
  465. if ex.is_Rational:
  466. return ex.q*x - ex.p
  467. if ex is I:
  468. _, factors = factor_list(x**2 + 1, x, domain=dom)
  469. return x**2 + 1 if len(factors) == 1 else x - I
  470. if ex is S.GoldenRatio:
  471. _, factors = factor_list(x**2 - x - 1, x, domain=dom)
  472. if len(factors) == 1:
  473. return x**2 - x - 1
  474. else:
  475. return _choose_factor(factors, x, (1 + sqrt(5))/2, dom=dom)
  476. if ex is S.TribonacciConstant:
  477. _, factors = factor_list(x**3 - x**2 - x - 1, x, domain=dom)
  478. if len(factors) == 1:
  479. return x**3 - x**2 - x - 1
  480. else:
  481. fac = (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
  482. return _choose_factor(factors, x, fac, dom=dom)
  483. if hasattr(dom, 'symbols') and ex in dom.symbols:
  484. return x - ex
  485. if dom.is_QQ and _is_sum_surds(ex):
  486. # eliminate the square roots
  487. ex -= x
  488. while 1:
  489. ex1 = _separate_sq(ex)
  490. if ex1 is ex:
  491. return ex
  492. else:
  493. ex = ex1
  494. if ex.is_Add:
  495. res = _minpoly_add(x, dom, *ex.args)
  496. elif ex.is_Mul:
  497. f = Factors(ex).factors
  498. r = sift(f.items(), lambda itx: itx[0].is_Rational and itx[1].is_Rational)
  499. if r[True] and dom == QQ:
  500. ex1 = Mul(*[bx**ex for bx, ex in r[False] + r[None]])
  501. r1 = dict(r[True])
  502. dens = [y.q for y in r1.values()]
  503. lcmdens = reduce(lcm, dens, 1)
  504. neg1 = S.NegativeOne
  505. expn1 = r1.pop(neg1, S.Zero)
  506. nums = [base**(y.p*lcmdens // y.q) for base, y in r1.items()]
  507. ex2 = Mul(*nums)
  508. mp1 = minimal_polynomial(ex1, x)
  509. # use the fact that in SymPy canonicalization products of integers
  510. # raised to rational powers are organized in relatively prime
  511. # bases, and that in ``base**(n/d)`` a perfect power is
  512. # simplified with the root
  513. # Powers of -1 have to be treated separately to preserve sign.
  514. mp2 = ex2.q*x**lcmdens - ex2.p*neg1**(expn1*lcmdens)
  515. ex2 = neg1**expn1 * ex2**Rational(1, lcmdens)
  516. res = _minpoly_op_algebraic_element(Mul, ex1, ex2, x, dom, mp1=mp1, mp2=mp2)
  517. else:
  518. res = _minpoly_mul(x, dom, *ex.args)
  519. elif ex.is_Pow:
  520. res = _minpoly_pow(ex.base, ex.exp, x, dom)
  521. elif ex.__class__ is sin:
  522. res = _minpoly_sin(ex, x)
  523. elif ex.__class__ is cos:
  524. res = _minpoly_cos(ex, x)
  525. elif ex.__class__ is tan:
  526. res = _minpoly_tan(ex, x)
  527. elif ex.__class__ is exp:
  528. res = _minpoly_exp(ex, x)
  529. elif ex.__class__ is CRootOf:
  530. res = _minpoly_rootof(ex, x)
  531. else:
  532. raise NotAlgebraic("%s does not seem to be an algebraic element" % ex)
  533. return res
  534. @public
  535. def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None):
  536. """
  537. Computes the minimal polynomial of an algebraic element.
  538. Parameters
  539. ==========
  540. ex : Expr
  541. Element or expression whose minimal polynomial is to be calculated.
  542. x : Symbol, optional
  543. Independent variable of the minimal polynomial
  544. compose : boolean, optional (default=True)
  545. Method to use for computing minimal polynomial. If ``compose=True``
  546. (default) then ``_minpoly_compose`` is used, if ``compose=False`` then
  547. groebner bases are used.
  548. polys : boolean, optional (default=False)
  549. If ``True`` returns a ``Poly`` object else an ``Expr`` object.
  550. domain : Domain, optional
  551. Ground domain
  552. Notes
  553. =====
  554. By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex``
  555. are computed, then the arithmetic operations on them are performed using the resultant
  556. and factorization.
  557. If ``compose=False``, a bottom-up algorithm is used with ``groebner``.
  558. The default algorithm stalls less frequently.
  559. If no ground domain is given, it will be generated automatically from the expression.
  560. Examples
  561. ========
  562. >>> from sympy import minimal_polynomial, sqrt, solve, QQ
  563. >>> from sympy.abc import x, y
  564. >>> minimal_polynomial(sqrt(2), x)
  565. x**2 - 2
  566. >>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2)))
  567. x - sqrt(2)
  568. >>> minimal_polynomial(sqrt(2) + sqrt(3), x)
  569. x**4 - 10*x**2 + 1
  570. >>> minimal_polynomial(solve(x**3 + x + 3)[0], x)
  571. x**3 + x + 3
  572. >>> minimal_polynomial(sqrt(y), x)
  573. x**2 - y
  574. """
  575. ex = sympify(ex)
  576. if ex.is_number:
  577. # not sure if it's always needed but try it for numbers (issue 8354)
  578. ex = _mexpand(ex, recursive=True)
  579. for expr in preorder_traversal(ex):
  580. if expr.is_AlgebraicNumber:
  581. compose = False
  582. break
  583. if x is not None:
  584. x, cls = sympify(x), Poly
  585. else:
  586. x, cls = Dummy('x'), PurePoly
  587. if not domain:
  588. if ex.free_symbols:
  589. domain = FractionField(QQ, list(ex.free_symbols))
  590. else:
  591. domain = QQ
  592. if hasattr(domain, 'symbols') and x in domain.symbols:
  593. raise GeneratorsError("the variable %s is an element of the ground "
  594. "domain %s" % (x, domain))
  595. if compose:
  596. result = _minpoly_compose(ex, x, domain)
  597. result = result.primitive()[1]
  598. c = result.coeff(x**degree(result, x))
  599. if c.is_negative:
  600. result = expand_mul(-result)
  601. return cls(result, x, field=True) if polys else result.collect(x)
  602. if not domain.is_QQ:
  603. raise NotImplementedError("groebner method only works for QQ")
  604. result = _minpoly_groebner(ex, x, cls)
  605. return cls(result, x, field=True) if polys else result.collect(x)
  606. def _minpoly_groebner(ex, x, cls):
  607. """
  608. Computes the minimal polynomial of an algebraic number
  609. using Groebner bases
  610. Examples
  611. ========
  612. >>> from sympy import minimal_polynomial, sqrt, Rational
  613. >>> from sympy.abc import x
  614. >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False)
  615. x**2 - 2*x - 1
  616. """
  617. generator = numbered_symbols('a', cls=Dummy)
  618. mapping, symbols = {}, {}
  619. def update_mapping(ex, exp, base=None):
  620. a = next(generator)
  621. symbols[ex] = a
  622. if base is not None:
  623. mapping[ex] = a**exp + base
  624. else:
  625. mapping[ex] = exp.as_expr(a)
  626. return a
  627. def bottom_up_scan(ex):
  628. """
  629. Transform a given algebraic expression *ex* into a multivariate
  630. polynomial, by introducing fresh variables with defining equations.
  631. Explanation
  632. ===========
  633. The critical elements of the algebraic expression *ex* are root
  634. extractions, instances of :py:class:`~.AlgebraicNumber`, and negative
  635. powers.
  636. When we encounter a root extraction or an :py:class:`~.AlgebraicNumber`
  637. we replace this expression with a fresh variable ``a_i``, and record
  638. the defining polynomial for ``a_i``. For example, if ``a_0**(1/3)``
  639. occurs, we will replace it with ``a_1``, and record the new defining
  640. polynomial ``a_1**3 - a_0``.
  641. When we encounter a negative power we transform it into a positive
  642. power by algebraically inverting the base. This means computing the
  643. minimal polynomial in ``x`` for the base, inverting ``x`` modulo this
  644. poly (which generates a new polynomial) and then substituting the
  645. original base expression for ``x`` in this last polynomial.
  646. We return the transformed expression, and we record the defining
  647. equations for new symbols using the ``update_mapping()`` function.
  648. """
  649. if ex.is_Atom:
  650. if ex is S.ImaginaryUnit:
  651. if ex not in mapping:
  652. return update_mapping(ex, 2, 1)
  653. else:
  654. return symbols[ex]
  655. elif ex.is_Rational:
  656. return ex
  657. elif ex.is_Add:
  658. return Add(*[ bottom_up_scan(g) for g in ex.args ])
  659. elif ex.is_Mul:
  660. return Mul(*[ bottom_up_scan(g) for g in ex.args ])
  661. elif ex.is_Pow:
  662. if ex.exp.is_Rational:
  663. if ex.exp < 0:
  664. minpoly_base = _minpoly_groebner(ex.base, x, cls)
  665. inverse = invert(x, minpoly_base).as_expr()
  666. base_inv = inverse.subs(x, ex.base).expand()
  667. if ex.exp == -1:
  668. return bottom_up_scan(base_inv)
  669. else:
  670. ex = base_inv**(-ex.exp)
  671. if not ex.exp.is_Integer:
  672. base, exp = (
  673. ex.base**ex.exp.p).expand(), Rational(1, ex.exp.q)
  674. else:
  675. base, exp = ex.base, ex.exp
  676. base = bottom_up_scan(base)
  677. expr = base**exp
  678. if expr not in mapping:
  679. if exp.is_Integer:
  680. return expr.expand()
  681. else:
  682. return update_mapping(expr, 1 / exp, -base)
  683. else:
  684. return symbols[expr]
  685. elif ex.is_AlgebraicNumber:
  686. if ex not in mapping:
  687. return update_mapping(ex, ex.minpoly_of_element())
  688. else:
  689. return symbols[ex]
  690. raise NotAlgebraic("%s does not seem to be an algebraic number" % ex)
  691. def simpler_inverse(ex):
  692. """
  693. Returns True if it is more likely that the minimal polynomial
  694. algorithm works better with the inverse
  695. """
  696. if ex.is_Pow:
  697. if (1/ex.exp).is_integer and ex.exp < 0:
  698. if ex.base.is_Add:
  699. return True
  700. if ex.is_Mul:
  701. hit = True
  702. for p in ex.args:
  703. if p.is_Add:
  704. return False
  705. if p.is_Pow:
  706. if p.base.is_Add and p.exp > 0:
  707. return False
  708. if hit:
  709. return True
  710. return False
  711. inverted = False
  712. ex = expand_multinomial(ex)
  713. if ex.is_AlgebraicNumber:
  714. return ex.minpoly_of_element().as_expr(x)
  715. elif ex.is_Rational:
  716. result = ex.q*x - ex.p
  717. else:
  718. inverted = simpler_inverse(ex)
  719. if inverted:
  720. ex = ex**-1
  721. res = None
  722. if ex.is_Pow and (1/ex.exp).is_Integer:
  723. n = 1/ex.exp
  724. res = _minimal_polynomial_sq(ex.base, n, x)
  725. elif _is_sum_surds(ex):
  726. res = _minimal_polynomial_sq(ex, S.One, x)
  727. if res is not None:
  728. result = res
  729. if res is None:
  730. bus = bottom_up_scan(ex)
  731. F = [x - bus] + list(mapping.values())
  732. G = groebner(F, list(symbols.values()) + [x], order='lex')
  733. _, factors = factor_list(G[-1])
  734. # by construction G[-1] has root `ex`
  735. result = _choose_factor(factors, x, ex)
  736. if inverted:
  737. result = _invertx(result, x)
  738. if result.coeff(x**degree(result, x)) < 0:
  739. result = expand_mul(-result)
  740. return result
  741. @public
  742. def minpoly(ex, x=None, compose=True, polys=False, domain=None):
  743. """This is a synonym for :py:func:`~.minimal_polynomial`."""
  744. return minimal_polynomial(ex, x=x, compose=compose, polys=polys, domain=domain)