/
polytools.py
4319 lines (3174 loc) · 111 KB
/
polytools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""User-friendly public interface to polynomial functions."""
import functools
import math
import mpmath
from mpmath.libmp import NoConvergence
from ..core import (Add, Basic, Expr, Integer, Mul, Tuple, expand_log,
expand_power_exp, oo, preorder_traversal)
from ..core.decorators import _sympifyit
from ..core.mul import _keep_coeff
from ..core.relational import Relational
from ..core.sympify import sympify
from ..domains import FF, QQ, ZZ
from ..domains.compositedomain import CompositeDomain
from ..logic.boolalg import BooleanAtom
from ..utilities import default_sort_key, group, sift
from ..utilities.iterables import is_iterable
from .constructor import construct_domain
from .groebnertools import groebner as _groebner
from .groebnertools import matrix_fglm
from .monomials import Monomial
from .orderings import build_product_order, lex, monomial_key
from .polyerrors import (CoercionFailedError, ComputationFailedError,
DomainError, GeneratorsError, GeneratorsNeededError,
MultivariatePolynomialError, PolificationFailedError,
PolynomialError, UnificationFailedError)
from .polyoptions import allowed_flags, build_options
from .polyutils import _is_coeff, _parallel_dict_from_expr, _sort_gens
from .rationaltools import together
from .rings import PolyElement
__all__ = ('Poly', 'PurePoly', 'parallel_poly_from_expr',
'degree', 'LC', 'LM', 'LT',
'div', 'rem', 'quo', 'exquo', 'half_gcdex', 'gcdex',
'invert', 'subresultants', 'resultant', 'discriminant', 'cofactors',
'gcd', 'lcm', 'terms_gcd', 'trunc',
'monic', 'content', 'primitive', 'compose', 'decompose',
'sqf_norm', 'sqf_part', 'sqf_list', 'sqf',
'factor_list', 'factor', 'count_roots',
'real_roots', 'nroots', 'eliminate',
'cancel', 'reduced', 'groebner', 'GroebnerBasis')
class Poly(Expr):
"""Generic class for representing polynomial expressions."""
is_commutative = True
is_Poly = True
_op_priority = 10.1
def __new__(cls, rep, *gens, **args):
"""Create a new polynomial instance out of something useful."""
opt = build_options(gens, args)
if is_iterable(rep, exclude=str):
if isinstance(rep, dict):
return cls._from_dict(rep, opt)
return cls._from_list(list(rep), opt)
rep = sympify(rep, evaluate=False)
if rep.is_Poly:
return cls._from_poly(rep, opt)
return cls._from_expr(rep, opt)
@classmethod
def new(cls, rep, *gens):
"""Construct :class:`Poly` instance from raw representation."""
if not isinstance(rep, PolyElement):
raise PolynomialError(f'invalid polynomial representation: {rep}')
if rep.ring.ngens != len(gens):
raise PolynomialError(f'invalid arguments: {rep}, {gens}')
obj = Expr.__new__(cls)
obj.rep = rep
obj.gens = gens
return obj
@classmethod
def from_dict(cls, rep, *gens, **args):
"""Construct a polynomial from a :class:`dict`."""
opt = build_options(gens, args)
return cls._from_dict(rep, opt)
@classmethod
def from_list(cls, rep, *gens, **args):
"""Construct a polynomial from a :class:`list`."""
opt = build_options(gens, args)
return cls._from_list(rep, opt)
@classmethod
def from_poly(cls, rep, *gens, **args):
"""Construct a polynomial from a polynomial."""
opt = build_options(gens, args)
return cls._from_poly(rep, opt)
@classmethod
def from_expr(cls, rep, *gens, **args):
"""Construct a polynomial from an expression."""
opt = build_options(gens, args)
return cls._from_expr(rep, opt)
@classmethod
def _from_dict(cls, rep, opt):
"""Construct a polynomial from a :class:`dict`."""
gens = opt.gens
if not gens:
raise GeneratorsNeededError(
"can't initialize from 'dict' without generators")
domain = opt.domain
if domain is None:
domain, rep = construct_domain(rep, opt=opt)
else:
for monom, coeff in rep.items():
rep[monom] = domain.convert(coeff)
ring = domain.poly_ring(*gens, order=opt.order)
return cls.new(ring.from_dict(rep), *gens)
@classmethod
def _from_list(cls, rep, opt):
"""Construct a polynomial from a :class:`list`."""
gens = opt.gens
if not gens:
raise GeneratorsNeededError("can't initialize from 'list'"
'without generators')
if len(gens) != 1:
raise MultivariatePolynomialError("'list' representation "
'not supported')
domain = opt.domain
if domain is None:
domain, rep = construct_domain(rep, opt=opt)
else:
rep = list(map(domain.convert, rep))
ring = domain.poly_ring(*gens)
return cls.new(ring.from_list(rep), *gens)
@classmethod
def _from_poly(cls, rep, opt):
"""Construct a polynomial from a polynomial."""
if cls != rep.__class__:
rep = cls.new(rep.rep, *rep.gens)
gens = opt.gens
if opt.composite or (gens and set(rep.gens) != set(gens)):
return cls._from_expr(rep.as_expr(), opt)
if gens and rep.gens != gens:
rep = rep.reorder(*gens)
if opt.domain:
rep = rep.set_domain(opt.domain)
elif opt.field:
rep = rep.to_field()
return rep
@classmethod
def _from_expr(cls, rep, opt):
"""Construct a polynomial from an expression."""
def _poly(expr, opt):
terms, poly_terms = [], []
for term in Add.make_args(expr):
factors, poly_factors = [], []
for factor in Mul.make_args(term):
if factor.is_Add:
poly_factors.append(_poly(factor, opt))
elif (factor.is_Pow and factor.base.is_Add and
factor.exp.is_Integer and factor.exp >= 0):
poly_factors.append(_poly(factor.base, opt)**factor.exp)
else:
factors.append(factor)
if not poly_factors:
terms.append(term)
else:
product = poly_factors[0]
for factor in poly_factors[1:]:
product *= factor
if factors:
factor = Mul(*factors)
if _is_coeff(factor, opt):
product *= factor
else:
(factor,), _opt = _parallel_dict_from_expr([factor], opt)
factor = cls._from_dict(factor, _opt)
product *= factor
poly_terms.append(product)
if not poly_terms:
(expr,), _opt = _parallel_dict_from_expr([expr], opt)
result = cls._from_dict(expr, _opt)
else:
result = poly_terms[0]
for term in poly_terms[1:]:
result += term
if terms:
term = Add(*terms)
if _is_coeff(term, opt):
result += term
else:
(term,), _opt = _parallel_dict_from_expr([term], opt)
term = cls._from_dict(term, _opt)
result += term
return result.reorder(*opt.gens, sort=opt.sort, wrt=opt.wrt)
rep = sympify(rep)
rep = rep.replace(lambda e: e.is_Pow and not e.is_Exp and
not e.exp.is_number, expand_power_exp)
rep = expand_log(rep)
if opt.expand is False:
(rep,), opt = _parallel_dict_from_expr([rep], opt)
return cls._from_dict(rep, opt)
return _poly(rep, opt.clone({'expand': False}))
def _hashable_content(self):
"""Allow Diofant to hash Poly instances."""
return self.rep, self.gens
__hash__ = Expr.__hash__
@property
def free_symbols(self):
"""
Free symbols of a polynomial expression.
Examples
========
>>> (x**2 + 1).as_poly().free_symbols
{x}
>>> (x**2 + y).as_poly().free_symbols
{x, y}
>>> (x**2 + y).as_poly(x).free_symbols
{x, y}
"""
symbols = set()
for gen in self.gens:
symbols |= gen.free_symbols
return symbols | self.free_symbols_in_domain
@property
def free_symbols_in_domain(self):
"""
Free symbols of the domain of ``self``.
Examples
========
>>> (x**2 + 1).as_poly().free_symbols_in_domain
set()
>>> (x**2 + y).as_poly().free_symbols_in_domain
set()
>>> (x**2 + y).as_poly(x).free_symbols_in_domain
{y}
"""
domain, symbols = self.domain, set()
if isinstance(domain, CompositeDomain):
for gen in domain.symbols:
symbols |= gen.free_symbols
elif domain.is_ExpressionDomain:
for coeff in self.coeffs():
symbols |= coeff.free_symbols
return symbols
@property
def args(self):
"""
Don't mess up with the core.
Examples
========
>>> (x**2 + 1).as_poly().args
(x**2 + 1, x)
"""
return (self.as_expr(),) + self.gens
@property
def is_number(self):
return self.as_expr().is_number
@property
def gen(self):
"""
Return the principal generator.
Examples
========
>>> (x**2 + 1).as_poly().gen
x
"""
return self.gens[0]
@property
def domain(self):
"""Get the ground domain of ``self``."""
return self.rep.ring.domain
def unify(self, other):
"""
Make ``self`` and ``other`` belong to the same domain.
Examples
========
>>> f, g = (x/2 + 1).as_poly(), (2*x + 1).as_poly()
>>> f
Poly(1/2*x + 1, x, domain='QQ')
>>> g
Poly(2*x + 1, x, domain='ZZ')
>>> F, G = f.unify(g)
>>> F
Poly(1/2*x + 1, x, domain='QQ')
>>> G
Poly(2*x + 1, x, domain='QQ')
"""
_, per, F, G = self._unify(other)
return per(F), per(G)
def _unify(self, other):
other = sympify(other)
if not other.is_Poly:
try:
return (self.domain, self.per, self.rep,
self.rep.ring(self.domain.convert(other)))
except CoercionFailedError as exc:
raise UnificationFailedError(f"can't unify {self} "
f'with {other}') from exc
newring = self.rep.ring.unify(other.rep.ring)
gens = newring.symbols
F, G = self.rep.set_ring(newring), other.rep.set_ring(newring)
cls = self.__class__
dom = newring.domain
def per(rep, dom=dom, gens=gens, remove=None):
if remove is not None:
gens = gens[:remove] + gens[remove + 1:]
if not gens:
return dom.to_expr(rep)
return cls.new(rep, *gens)
return dom, per, F, G
def per(self, rep, *gens, remove=None):
"""
Create a Poly out of the given representation.
Examples
========
>>> a = (x**2 + 1).as_poly()
>>> R = ZZ.inject(x)
>>> a.per(R.from_list([ZZ(1), ZZ(1)]), y)
Poly(y + 1, y, domain='ZZ')
"""
if not gens:
gens = self.gens
if remove is not None:
gens = gens[:remove] + gens[remove + 1:]
if not gens:
return self.domain.to_expr(rep)
return self.__class__.new(rep, *gens)
def set_domain(self, domain):
"""Set the ground domain of ``self``."""
opt = build_options(self.gens, {'domain': domain})
rep = self.rep.set_domain(opt.domain)
return self.per(rep)
def set_modulus(self, modulus):
"""
Set the modulus of ``self``.
Examples
========
>>> (5*x**2 + 2*x - 1).as_poly().set_modulus(2)
Poly(x**2 + 1, x, modulus=2)
"""
opt = build_options(self.gens, {'modulus': modulus})
rep = self.rep.set_domain(FF(opt.modulus))
return self.per(rep)
def get_modulus(self):
"""
Get the modulus of ``self``.
Examples
========
>>> (x**2 + 1).as_poly(modulus=2).get_modulus()
2
"""
domain = self.domain
if domain.is_FiniteField:
return Integer(domain.order)
raise PolynomialError('not a polynomial over a Galois field')
def _eval_subs(self, old, new):
"""Internal implementation of :func:`~diofant.core.basic.Basic.subs`."""
if old in self.gens:
if new.is_number:
return self.eval(old, new)
try:
return self.replace(old, new)
except PolynomialError:
pass
return self.as_expr().subs({old: new})
def exclude(self):
"""
Remove unnecessary generators from ``self``.
Examples
========
>>> (a + x).as_poly(a, b, c, d, x).exclude()
Poly(a + x, a, x, domain='ZZ')
"""
rep = self.rep
if rep.is_ground:
return self
for x in rep.ring.symbols:
try:
rep = rep.drop(x)
except ValueError:
pass
return self.per(rep, *rep.ring.symbols)
def replace(self, x, y=None):
"""
Replace ``x`` with ``y`` in generators list.
Examples
========
>>> (x**2 + 1).as_poly().replace(x, y)
Poly(y**2 + 1, y, domain='ZZ')
"""
if y is None:
if self.is_univariate:
x, y = self.gen, x
else:
raise PolynomialError(
'syntax supported only in univariate case')
if x == y:
return self
if x in self.gens and y not in self.gens:
dom = self.domain
if not isinstance(dom, CompositeDomain) or y not in dom.symbols:
gens = list(self.gens)
gens[gens.index(x)] = y
rep = dom.poly_ring(*gens).from_dict(dict(self.rep))
return self.per(rep, *gens)
raise PolynomialError(f"can't replace {x} with {y} in {self}")
def reorder(self, *gens, **args):
"""
Efficiently apply new order of generators.
Examples
========
>>> (x**2 + x*y**2).as_poly().reorder(y, x)
Poly(y**2*x + x**2, y, x, domain='ZZ')
"""
opt = build_options([], args)
if not gens:
gens = _sort_gens(self.gens, opt=opt)
elif set(self.gens) != set(gens):
raise PolynomialError(
'generators list can differ only up to order of elements')
rep = self.rep
new_ring = rep.ring.clone(symbols=gens)
rep = rep.set_ring(new_ring)
return self.per(rep, *gens)
def has_only_gens(self, *gens):
"""
Return ``True`` if ``Poly(f, *gens)`` retains ground domain.
Examples
========
>>> (x*y + 1).as_poly(x, y, z).has_only_gens(x, y)
True
>>> (x*y + z).as_poly(x, y, z).has_only_gens(x, y)
False
"""
indices = set()
for gen in gens:
try:
index = self.gens.index(gen)
except ValueError as exc:
raise GeneratorsError(f"{self} doesn't have "
f'{gen} as generator') from exc
indices.add(index)
for monom in self.monoms():
for i, elt in enumerate(monom):
if i not in indices and elt:
return False
return True
def to_ring(self):
"""
Make the ground domain a ring.
Examples
========
>>> (x**2 + 1).as_poly(field=True).to_ring()
Poly(x**2 + 1, x, domain='ZZ')
"""
return self.set_domain(self.domain.ring)
def to_field(self):
"""
Make the ground domain a field.
Examples
========
>>> (x**2 + 1).as_poly().to_field()
Poly(x**2 + 1, x, domain='QQ')
"""
return self.set_domain(self.domain.field)
def to_exact(self):
"""
Make the ground domain exact.
Examples
========
>>> (x**2 + 1.0).as_poly().to_exact()
Poly(x**2 + 1, x, domain='QQ')
"""
return self.set_domain(self.domain.get_exact())
def retract(self, field=None):
"""
Recalculate the ground domain of a polynomial.
Examples
========
>>> f = (x**2 + 1).as_poly(domain=QQ.inject(y))
>>> f
Poly(x**2 + 1, x, domain='QQ[y]')
>>> f.retract()
Poly(x**2 + 1, x, domain='ZZ')
>>> f.retract(field=True)
Poly(x**2 + 1, x, domain='QQ')
"""
dom, rep = construct_domain(self.as_dict(),
field=field,
composite=isinstance(self.domain, CompositeDomain) or None,
extension=not self.domain.is_ExpressionDomain)
return self.from_dict(rep, *self.gens, domain=dom)
def coeffs(self, order=None):
"""
Returns all non-zero coefficients from ``self`` in lex order.
Examples
========
>>> (x**3 + 2*x + 3).as_poly().coeffs()
[1, 2, 3]
See Also
========
all_coeffs
coeff_monomial
"""
return [coeff for _, coeff in self.terms(order)]
def monoms(self, order=None):
"""
Returns all non-zero monomials from ``self`` in lex order.
Examples
========
>>> (x**2 + 2*x*y**2 + x*y + 3*y).as_poly().monoms()
[(2, 0), (1, 2), (1, 1), (0, 1)]
"""
return [monom for monom, _ in self.terms(order)]
def terms(self, order=None):
"""
Returns all non-zero terms from ``self`` in lex order.
Examples
========
>>> (x**2 + 2*x*y**2 + x*y + 3*y).as_poly().terms()
[((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)]
"""
rep = self.rep
if order is None:
order = rep.ring.order
else:
opt = build_options(self.gens, {'order': order})
order = opt.order
return [(m, self.domain.to_expr(c))
for m, c in sorted(rep.items(),
key=lambda monom: order(monom[0]),
reverse=True)]
def all_coeffs(self):
"""
Returns all coefficients from a univariate polynomial ``self``.
Examples
========
>>> (x**3 + 2*x - 1).as_poly().all_coeffs()
[-1, 2, 0, 1]
"""
return [self.domain.to_expr(c) for c in self.rep.all_coeffs()]
def termwise(self, func, *gens, **args):
"""
Apply a function to all terms of ``self``.
Examples
========
>>> def func(k, coeff):
... k = k[0]
... return coeff//10**(2-k)
>>> (x**2 + 20*x + 400).as_poly().termwise(func)
Poly(x**2 + 2*x + 4, x, domain='ZZ')
"""
terms = {}
for monom, coeff in self.terms():
result = func(monom, coeff)
if isinstance(result, tuple):
monom, coeff = result
else:
coeff = result
if coeff:
if monom not in terms:
terms[monom] = coeff
else:
raise PolynomialError(f'{monom} monomial was generated twice')
return self.from_dict(terms, *(gens or self.gens), **args)
def length(self):
"""
Returns the number of non-zero terms in ``self``.
Examples
========
>>> (x**2 + 2*x - 1).as_poly().length()
3
"""
return len(self.as_dict())
def as_dict(self, native=False):
"""
Switch to a :class:`dict` representation.
Examples
========
>>> (x**2 + 2*x*y**2 - y).as_poly().as_dict()
{(0, 1): -1, (1, 2): 2, (2, 0): 1}
"""
if native:
return dict(self.rep)
return {k: self.domain.to_expr(v) for k, v in self.rep.items()}
def as_expr(self, *gens):
"""
Convert a Poly instance to an Expr instance.
Examples
========
>>> f = (x**2 + 2*x*y**2 - y).as_poly()
>>> f.as_expr()
x**2 + 2*x*y**2 - y
>>> f.as_expr({x: 5})
10*y**2 - y + 25
>>> f.as_expr(5, 6)
379
"""
if not gens:
gens = self.gens
elif len(gens) == 1 and isinstance(gens[0], dict):
mapping = gens[0]
gens = list(self.gens)
for gen, value in mapping.items():
try:
index = gens.index(gen)
except ValueError as exc:
raise GeneratorsError(f"{self} doesn't have "
f'{gen} as generator') from exc
gens[index] = value
rep = self.rep
return rep.ring.to_expr(rep).subs(dict(zip(self.gens, gens)))
def inject(self, front=False):
"""
Inject ground domain generators into ``self``.
Examples
========
>>> f = (x**2*y + x*y**3 + x*y + 1).as_poly(x)
>>> f.inject()
Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ')
>>> f.inject(front=True)
Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ')
"""
result = self.rep.inject(front=front)
return self.new(result, *result.ring.symbols)
def eject(self, *gens):
"""
Eject selected generators into the ground domain.
Examples
========
>>> f = (x**2*y + x*y**3 + x*y + 1).as_poly()
>>> f.eject(x)
Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]')
>>> f.eject(y)
Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]')
"""
dom = self.domain
if not dom.is_Numerical:
raise DomainError(f"can't eject generators over {dom}")
result = self.rep.copy()
result = result.eject(*gens)
return self.new(result, *result.ring.symbols)
def drop(self, *gens):
"""
Drop selected generators, if possible.
Examples
========
>>> f = (x + 1).as_poly(x, y)
>>> f.drop(y)
Poly(x + 1, x, domain='ZZ')
>>> f.drop(x)
Traceback (most recent call last):
...
ValueError: can't drop (Symbol('x'),)
"""
result = self.rep.copy()
result = result.drop(*gens)
return self.new(result, *result.ring.symbols)
def terms_gcd(self):
"""
Remove GCD of terms from the polynomial ``self``.
Examples
========
>>> (x**6*y**2 + x**3*y).as_poly().terms_gcd()
((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ'))
"""
J, result = self.rep.terms_gcd()
return J, self.per(result)
def quo_ground(self, coeff):
"""
Quotient of ``self`` by a an element of the ground domain.
Examples
========
>>> (2*x + 4).as_poly().quo_ground(2)
Poly(x + 2, x, domain='ZZ')
>>> (2*x + 3).as_poly().quo_ground(2)
Poly(x + 1, x, domain='ZZ')
"""
result = self.rep.quo_ground(coeff)
return self.per(result)
def exquo_ground(self, coeff):
"""
Exact quotient of ``self`` by a an element of the ground domain.
Examples
========
>>> (2*x + 4).as_poly().exquo_ground(2)
Poly(x + 2, x, domain='ZZ')
>>> (2*x + 3).as_poly().exquo_ground(2)
Traceback (most recent call last):
...
ExactQuotientFailedError: 2 does not divide 3 in ZZ
"""
result = self.rep.exquo_ground(coeff)
return self.per(result)
def div(self, other, auto=True):
"""
Polynomial division with remainder of ``self`` by ``other``.
Examples
========
>>> (x**2 + 1).as_poly().div((2*x - 4).as_poly())
(Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ'))
>>> (x**2 + 1).as_poly().div((2*x - 4).as_poly(), auto=False)
(Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ'))
"""
dom, per, F, G = self._unify(other)
retract = False
if auto and dom.is_Ring and not dom.is_Field:
F, G = F.set_domain(F.ring.domain.field), G.set_domain(G.ring.domain.field)
retract = True
q, r = divmod(F, G)
if retract:
try:
Q, R = q.set_domain(q.ring.domain.ring), r.set_domain(r.ring.domain.ring)
except CoercionFailedError:
pass
else:
q, r = Q, R
return per(q), per(r)
def rem(self, other, auto=True):
"""
Computes the polynomial remainder of ``self`` by ``other``.
Examples
========
>>> (x**2 + 1).as_poly().rem((2*x - 4).as_poly())
Poly(5, x, domain='ZZ')
>>> (x**2 + 1).as_poly().rem((2*x - 4).as_poly(), auto=False)
Poly(x**2 + 1, x, domain='ZZ')
"""
dom, per, F, G = self._unify(other)
retract = False
if auto and dom.is_Ring and not dom.is_Field:
F, G = F.set_domain(F.ring.domain.field), G.set_domain(G.ring.domain.field)
retract = True
r = F % G
if retract:
try:
r = r.set_domain(r.ring.domain.ring)
except CoercionFailedError:
pass
return per(r)
def quo(self, other, auto=True):
"""
Computes polynomial quotient of ``self`` by ``other``.
Examples
========
>>> (x**2 + 1).as_poly().quo((2*x - 4).as_poly())
Poly(1/2*x + 1, x, domain='QQ')
>>> (x**2 - 1).as_poly().quo((x - 1).as_poly())
Poly(x + 1, x, domain='ZZ')
"""
dom, per, F, G = self._unify(other)
retract = False
if auto and dom.is_Ring and not dom.is_Field:
F, G = F.set_domain(F.ring.domain.field), G.set_domain(G.ring.domain.field)
retract = True
q = F // G
if retract:
try: