This repository has been archived by the owner on Jan 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSinglePolynomial.py
1580 lines (1176 loc) · 55.2 KB
/
SinglePolynomial.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
from __future__ import annotations
from MultyPolynomial import MultyPolinomial, LenghtError, Self, Never, Callable, Number, overload, match, floor, randint, uniform
Unknowns = str
Powers = dict[int,Number]
Integrals = dict[int,list[str|Number]]
class SinglePolynomial(MultyPolinomial):
"This object is used to create and match the needs for a polinomial in a single variable"
#the only variables used by the object
__slots__ = ()
## SOME INITIALIZATION && CLASSMETHODS ##
def __new(self, powers_coefficients:Powers, unknown:Unknowns, integrals_coefficients:Integrals|None=None) -> None:
"""
Before creating the object, it checks that every argument is given in the right format
"""
#to not change furthermore these checks, integrals_coefficients is initialized as dict()
if integrals_coefficients is None:
integrals_coefficients={}
if type(unknown) is not Unknowns:
raise TypeError("'unknown' has to be a string")
if type(powers_coefficients) is not Powers.__origin__ :
raise TypeError("'powers_coefficients' has to be a dict")
if type(integrals_coefficients) is not Integrals.__origin__ :
raise TypeError("'integrals_coefficients' has to be a dict")
if not all(isinstance(q,int) for q in powers_coefficients|integrals_coefficients):
raise LenghtError("All the key used in both 'powers_coefficients' and 'integrals_coefficients' have to be numbers of type int")
for coef in powers_coefficients.values():
self._check__is_Number(coef,"All the value used in 'powers_coefficients' have to be a Number")
for coef in integrals_coefficients.values():
self._check__is_Number(coef[1],"All the value used in 'integrals_coefficients' have to be list[str,Number]")
@overload
def __init__(self, powers_coefficients:Powers, unknown:Unknowns) -> None:
"""
It creates the Polinoms giving to it a dictionary for the coefficient for each needed combination on power to each unknown:
- powers = {'0':1,'1':-1,'3':3} -> 1*x^0-1*x^1+3*x^3
a string for the unknowns:
- unknown = 'x'
"""
@overload
def __init__(self, powers_coefficients:Powers, unknown:Unknowns, integrals_coefficients:Integrals|None=None) -> None:
"""
It creates the Polinoms giving to it a dictionary for the coefficient for each needed combination on power to each unknown:
- powers = {'0':1,'1':-1,'3':3} -> 1*x^0-1*x^1+3*x^3
a string for the unknowns:
- unknown = 'x'
and eventually a dictonary for the "integral coefficient" dictionary:
- integrals_coefficients = {'1':['C0',3]} -> 3*C0*x
"""
def __init__(self, powers_coefficients:Powers, unknown:Unknowns, integrals_coefficients:Integrals|None=None) -> None:
self.__new(powers_coefficients,unknown,integrals_coefficients)
self._pcoef = powers_coefficients
self._unkn = unknown
if integrals_coefficients is None:
self._icoef = {}
else:
self._icoef = integrals_coefficients
@classmethod
def fromSingle(cls: type[Self], s:SinglePolynomial) -> Self:
"""
Given another SinglePolynomial it creates a new SinglePolynomial with the same informations
"""
return super().fromMulty(s)
@classmethod
def fromMulty(cls: type[Self], m:MultyPolinomial) -> Self:
"""
Given another MultyPolinomial it creates a new SinglePolynomial with the same informations
"""
if len(m._unkn) !=1:
degs = tuple(m.degs())
if sum(1 if i else 0 for i in degs)!=1:
raise LenghtError(f"{m!r} has too many Unknowns: {m.unknown}")
for pos,unkn,deg in zip(*zip(*enumerate(m._unkn)),degs):
if not deg:
continue
return cls({int(power.split("-")[pos]):coef for power,coef in m._pcoef.items() if coef},unkn,{int(p.split("-")[pos]):c.copy() for p,c in m._icoef.items() if c[1]})
return cls({int(power):coef for power,coef in m._pcoef.items() if coef},m._unkn[0],{int(p):c.copy() for p,c in m._icoef.items() if c[1]})
@overload
@classmethod
def fromText(cls: type[Self], text:str) -> Self:
"""
Given a string of text it tries to create the polinom.
the string has to be formatted, writing every multiplication *, even between coef and unknown. The exponential has to be written with ^. It doesn't understand parenthesis
More complex form can be achieved by applaying math operation between multiple SinglePolynomial
"""
@overload
@classmethod
def fromText(cls: type[Self], text:str, unknown:Unknowns="x") -> Self:
"""
Given a string of text it tries to create the polinom.
the string has to be formatted, writing every multiplication *, even between coef and unknown. The exponential has to be written with ^. It doesn't understand parenthesis
More complex form can be achieved by applaying math operation between multiple SinglePolynomial
If a unknown str is given, it will be used when not present in text
"""
@overload
@classmethod
def fromText(cls: type[Self], text:str, unknown:Unknowns="", integrals_coefficients:Integrals|None={}) -> Self:
"""
Given a string of text it tries to create the polinom.
the string has to be formatted, writing every multiplication *, even between coef and unknown. The exponential has to be written with ^. It doesn't understand parenthesis
More complex form can be achieved by applaying math operation between multiple SinglePolynomial
If a unknown str is given, it will be used when not present in text
integrals_coefficients have to be in the right format.
if unknown = "z", each item has to be: 3: ['C0',5] -> 5*C0*z^3
"""
@classmethod
def fromText(cls: type[Self], text:str, temp_unknown:Unknowns="x", integrals_coefficients:Integrals|None=None) -> Self:
num = r'^[+-]?(?:(?:\d+)?(?:\.)?(?:\d+)?)$'
unknown = ""
t = {}
text = text.replace("-","+-")
if text.startswith("+"):
text = text[1:]
for part in text.split("+"):
power = "0"
coef = "1"
for p in part.split("*"):
if not p:
continue
if p.startswith("-"):
coef+=f"*(-1)"
p=p[1:]
if "^" in p:
i, val = p.split("^")
x = match(num,i)
if x:
coef+=f"*({i}**{val})"
continue
if i == unknown:
power+=f"+{val}"
continue
elif unknown:
raise ValueError("Too many Unknowns for this SinglePolynomial")
unknown=i
power=f"{val}"
continue
x = match(num,p)
if x:
coef+=f"*{p}"
continue
elif p == unknown:
power+="+1"
continue
elif unknown:
raise ValueError("Too many Unknowns for this SinglePolynomial")
unknown=p
power="1"
power = eval(power)
coef = eval(coef)
if power in t:
t[power] += coef
continue
t[power] = coef
if not unknown:
unknown = temp_unknown
if integrals_coefficients:
if not all(isinstance(p,int) for p in integrals_coefficients):
raise LenghtError("All the key used in 'integrals_coefficients' have to be numbers of type int")
return cls(t,unknown, integrals_coefficients)
return cls(t,unknown, {})
@overload
@classmethod
def one(cls: type[Self]) -> Self:
"""
This classmethod creates a SignlePolinomial with only the coef 1
"""
@overload
@classmethod
def one(cls: type[Self], unknowns:Unknowns="x") -> Self:
"""
This classmethod creates a SinglePolinomial with only the coef 1
If unknowns are given, it initializes it with it
"""
@classmethod
def one(cls: type[Self], unknowns:Unknowns="x") -> Self:
return cls({0:1},unknowns,{})
@overload
@classmethod
def zero(cls: type[Self]) -> Self:
"""
This classmethod creates a SinglePolinomial with only the coef 0
"""
@overload
@classmethod
def zero(cls: type[Self], unknown:Unknowns="x") -> Self:
"""
This classmethod creates a SinglePolinomial with only the coef 0
If unknown is given, it initializes it with it
"""
@classmethod
def zero(cls: type[Self], unknown:Unknowns="x") -> Self:
return cls({0:0},unknown,{})
@overload
@classmethod
def random(cls: type[Self], maxdeg:int) -> Self:
"""
This classmethod creates a random SinglePolinomial with at maximum the given degree to every monom. It is a lil' junk
The unknown will be 'x'
"""
@overload
@classmethod
def random(cls: type[Self], maxdeg:int, unknown:str="x") -> Self:
"""
This classmethod creates a random SinglePolinomial with at maximum the given degree to every monom. It is a lil' junk
it will use the given unknown
"""
@classmethod
def random(cls: type[Self], maxdeg:int, unknown:str="x") -> Self:
t={}
m = max(5,maxdeg)
v = randint(randint(1,m-1),m+1)
for i in range(v):
u = randint(0,maxdeg)
if u in t:
t[u]-=uniform(-m,m)*(-1)**i
else:
t[u]=randint(-v,v)*(-1)**i
if not t:
t[0] = 0
return cls(t,unknown,{})
## SOME PROPERTIES TO ACCESS VARIABLES QUICKLY ##
@property
def unknown(self) -> Unknowns:
"tuple of the unknown"
return self._unkn
@unknown.setter
def unknown(self, unknowns:Unknowns) -> None:
"tuple of the unknown"
if not isinstance(unknowns, Unknowns):
raise TypeError("'unknown' has to be a string")
self._unkn = unknowns
@property
def powers(self) -> Powers:
"dictionary of the coefficients"
return self._pcoef
@powers.setter
def powers(self, powers_coefficients:Powers) -> None:
"dictionary of the coefficients"
if not isinstance(powers_coefficients, Powers.__origin__):
raise TypeError("'powers_coefficients' has to be a dict")
if not all(isinstance(p,int) for p in powers_coefficients):
raise LenghtError("The lenght of all the keys inthe given Powers has to be the same as unknown")
self._pcoef = powers_coefficients
@property
def integrals(self) -> Integrals:
"dictionary of the integrals costants"
return self._icoef
@integrals.setter
def integrals(self, integrals_coefficients:Integrals) -> None:
"dictionary of the coefficients"
if not isinstance(integrals_coefficients, Integrals.__origin__):
raise TypeError("'integrals_coefficients' has to be a dict")
elif not all(isinstance(p,int) for p in integrals_coefficients):
raise LenghtError("The lenght of all the keys inthe given Integrals has to be the same as unknown")
self._icoef = integrals_coefficients
## SOME INTERESTING METHODS ##
def toMulty(self) -> MultyPolinomial:
"It convert this single polynomial into a multy one"
return MultyPolinomial({str(power):coef for power,coef in self._pcoef.items()},(self._unkn,),{str(power):coef.copy() for power,coef in self._icoef.items()})
def __len__(self) -> int:
"""
return the number of unknowns
"""
return 1
def deg(self) -> int:
"""
it returns the maximum degree of the polynomial
"""
return max(0,0,*tuple(power for power,coef in self._pcoef.items() if coef),*tuple(power for power,coef in self._icoef.items() if coef))
def degs(self) -> int:
"""
it returns the maximum degree of the polynomial
"""
return self.deg()
## STRING METHODS ##
def __str__(self) -> str:
"""
string of the MultyPolinomial
if this MultyPolinomial has any Integrals, it will raise an error if used for fromText()
Before to do so, is best practice to check if Integrals are present with has_integrals_const() or by passing 'i' at __format__()
"""
s = ""
h = ("+","-")
for power,coef in sorted(self._pcoef.items(),key=lambda x:x[0],reverse=True):
if not coef:
continue
if coef == floor(coef):
coef = floor(coef)
if power and abs(coef)==1:
if coef> 0:
s+="+"
else:
s+="-"
else:
s+=f"{coef:+}"
if not power:
continue
if not s[-1] in h:
s+=f"*{self._unkn}"
else:
s+=f"{self._unkn}"
if power>=2:
s+=f"^{power}"
for power,coef in sorted(self._icoef.items(),key=lambda x:x[0],reverse=True):
if not coef[1]:
continue
if coef[1] == floor(coef[1]):
coef[1] = floor(coef[1])
if abs(coef[1])==1:
if coef[1]> 0:
s+="+"
else:
s+="-"
else:
s+=f"{coef[1]:+}*"
s+=coef[0]
if not power:
continue
if not s[-1] in h:
s+=f"*{self._unkn}"
else:
s+=f"{self._unkn}"
if power>=2:
s+=f"^{power}"
if not s:
return "0"
return s.lstrip("+")
def __format__(self, __format_spec: str) -> str:
"""
The __format_spec can format individually the polynomial coef individually and the whole polynomial object,
it is olso possible to format it without the integration parts. To get this, the formatting moda has to follow this:
'[integrals][numbers][!!monomials][;;[polinomial]]'
- integrals, if 'i' is given, integrals will be ignored, wherealse if 'ii' is given, the non integral part wuill be ignored. other formatting modes will be given to numbers
- numbers, are the formatting spec for the numbers, following the standard formatting for numbers
- monomials, are the formatting spec for the monomials as string
- MultyPolinomial, are the formatting spec for the MultyPolinomials as string
"""
if __format_spec.startswith("ii"):
numbers = __format_spec[2:]
starter = False
breaker = True
elif __format_spec.startswith("i"):
numbers = __format_spec[1:]
starter = True
breaker = True
else:
numbers = __format_spec
starter = True
breaker = False
polynomial=monomials=""
if "!!" in numbers:
numbers,monomials = numbers.split("!!")
if ";;" in numbers:
numbers,polynomial = numbers.split(";;")
elif ";;" in monomials:
monomials,polynomial = monomials.split(";;")
h = ("+","-")
s = ""
if starter:
for power in sorted(self._pcoef.keys(),reverse=True):
ks = ""
coef = self._pcoef[power]
if not coef:
continue
ks = f"{coef:{numbers}}"
if not power:
s+=f'{"+"*(not ks.startswith(h))}{f"{ks:{monomials}}"}'
continue
ks+=f"*{self._unkn}"
if power>=2:
ks+=f"^{power}"
ks= f'{ks:{monomials}}'
s+=f'{"+"*(not ks.startswith(h))}{ks}'
if breaker:
if not s:
return f"""{f"{f'{0:{numbers}}':{monomials}}":{polynomial}}"""
return f"{s.strip('+'):{polynomial}}"
for power in sorted(self._icoef.keys(),reverse=True):
ks = ""
coef = self._icoef[power]
if not coef[1]:
continue
ks = f"{coef[1]:{numbers}}*{coef[0]}"
if not power:
s+=f'{"+"*(not ks.startswith(h))}{f"{ks:{monomials}}"}'
continue
ks+=f"*{self._unkn}"
if power>=2:
ks+=f"^{power}"
ks= f'{ks:{monomials}}'
s+=f'{"+"*(not ks.startswith(h))}{ks}'
if not s:
return f"""{f"{f'{0:{numbers}}':{monomials}}":{polynomial}}"""
return f"{s.strip('+'):{polynomial}}"
@staticmethod
def _get_key_0(__len:Never) -> int:
"""
it returns just 0
"""
return 0
## OPERATION OVER MULTIVARIATIVE POLYNOMIALS ##
@overload
def __call__(self, values:Number) -> tuple[Number,str]:
"""
values can be a number if and only if Unknowns has only one element, and evaluate this polynomial in the given value
To make only a partial evaluation, use evaluate or evaluate_ip methods
It returns the number of the evaluation and the string representing the Integrals consts
"""
@overload
def __call__(self, values:Number, __ignore:bool=False) -> Number | tuple[Number,str]:
"""
It returns the number of the evaluation and the string representing the Integrals consts
if __ignore is give True, only the evaluation will be returned
"""
def __call__(self, values:Number, __ignore:bool=False) -> Number | tuple[Number,str]:
t = self.__format__("i")
k = self.__format__("ii")
if __ignore:
return eval(t.replace(self._unkn,str(values)).replace("^","**"))
t=t.replace(self._unkn,str(values))
k=k.replace(self._unkn,str(values))
return eval(t.replace("^","**")), k
def evaluate(self, values:Number) -> Self:
"""
It returns an evaluation as polynomial, its unknown will be kept
"""
p = 0
i = {}
if self._icoef:
i[0]=["C0",1]
for power,coef in self._pcoef.items():
p+=coef*values**power
return self.__class__({0:p},self._unkn,i)
def evaluate_ip(self, values:Number) -> None:
"""
It updates itself evaluating in the given value as polynomial, its unknown will be kept
"""
p = 0
if self._icoef:
self._icoef.clear()
self._icoef[0]=["C0",1]
for power,coef in self._pcoef.items():
p+=coef*values**power
self._pcoef.clear()
self._pcoef[0]=p
def derive(self) -> Self:
"It derives the SinglePolynomial in its unknnown"
return self.__class__({power-1:coef*power for power, coef in self._pcoef.items() if power and coef}, self._unkn, {power-1:[coef[0],coef[1]*power] for power, coef in self._icoef.items() if power and coef[1]})
def derive_ip(self) -> None:
"It derives the SinglePolynomial in its unknnown"
p = {power-1:coef*power for power, coef in self._pcoef.items() if power and coef}
i = {power-1:[coef[0],coef[1]*power] for power, coef in self._icoef.items() if power and coef[1]}
self._pcoef.clear()
self._pcoef.update(p)
self._icoef.clear()
self._icoef.update(i)
def derive_n(self, __n:int=1) -> Self:
"It derives the given number of times the SinglePolynomial in its unknnown"
s = self.copy()
for _ in range(__n):
s.derive_ip()
return s
def derive_n_ip(self, __n:int=1) -> None:
"It derives the given number of times the SinglePolynomial in its unknnown"
for _ in range(__n):
self.derive_ip()
def partial(self, unknown:str) -> Self|MultyPolinomial:
"""
It makes a partial derivation in the given unknown. If a different unknown is given, a MultyPolynomial will be returned
"""
if unknown == self._unkn:
return self.derive()
return MultyPolinomial.zero(self._unkn,unknown)
def partial_ip(self, unknown:str) -> None:
"""
It makes a partial derivation in the given unknown
"""
if unknown == self._unkn:
return self.derive_ip()
raise ValueError(f"the given unknown {unknown} doesn't match up with {self._unkn}. Consider convert this SinglePolynomial to MultyPolynomial before")
@overload
def partial_n(self, *unknown:str) -> Self|MultyPolinomial:
"""
it makes sequentially all the partial derivations in the given unknown.
If a different unknown is given, a MultyPolynomial will be returned
"""
@overload
def partial_n(self, **kwargs:int) -> Self|MultyPolinomial:
"""
it makes sequentially all the partial derivations in the given unknown by the given number
If a different unknown is given, a MultyPolynomial will be returned
"""
@overload
def partial_n(self, *unknown:str, **kwargs:int) -> Self|MultyPolinomial:
"""
it makes sequentially all the partial derivations in the given unknown and by given unknown by the given number
If a different unknown is given, a MultyPolynomial will be returned
"""
def partial_n(self, *unknown:str, **kwargs:int) -> Self|MultyPolinomial:
if all(u == self._unkn for u in unknown|kwargs.keys()):
return self.derive_n(len(unknown)+kwargs.get(self._unkn,0))
return self.toMulty().partial_n(*unknown, **kwargs)
@overload
def partial_n_ip(self, *unknown:str) -> None:
"""
it makes sequentially all the partial derivations in the given unknown
"""
@overload
def partial_n_ip(self, **kwargs:int) -> None:
"""
it makes sequentially all the partial derivations in the given unknown by the given number
"""
@overload
def partial_n_ip(self, *unknown:str, **kwargs:int) -> None:
"""
it makes sequentially all the partial derivations in the given unknown and by given unknown by the given number
"""
def partial_n_ip(self, *unknown:str, **kwargs:int) -> None:
if all(u == self._unkn for u in unknown|kwargs.keys()):
return self.derive_n_ip(len(unknown)+kwargs.get(self._unkn,0))
raise ValueError(f"the given unknowns {unknown|kwargs.keys()} doesn't match up with {self._unkn}. Consider convert this SinglePolynomial to MultyPolynomial before")
def integral(self) -> Self:
"""
It integrates the SinglePolinomial
"""
return self.__class__({power+1:coef*(power+1) for power, coef in self._pcoef.items() if power and coef}, self._unkn, {power+1:[coef[0],coef[1]*(power+1)] for power, coef in self._icoef.items() if coef[1]}|{0:[f"C{len(self._icoef)}",1]})
def integral_ip(self) -> None:
"""
It integrates the MultyPolinomial
"""
icoef = self._icoef.copy()
pcoef=self._pcoef.copy()
self._pcoef.clear()
self._icoef.clear()
self._pcoef.update({power+1:coef/(power+1) for coef,power in pcoef.items() if coef})
self._icoef.update({power+1:coef/(power+1) for coef,power in icoef.items() if coef}|{0:[f"C{len(icoef)}",1]})
@overload
def integral_n(self, *unknown:str) -> Self|MultyPolinomial:
"""
it makes sequentially all the integrations in the given unknown
If a different unknown is given, a MultyPolynomial will be returned
"""
@overload
def integral_n(self, **kwargs:int) -> Self|MultyPolinomial:
"""
it makes sequentially all the integrations in the given unknown by the given number
If a different unknown is given, a MultyPolynomial will be returned
"""
@overload
def integral_n(self, *unknown:str, **kwargs:int) -> Self|MultyPolinomial:
"""
it makes sequentially all the integrations in the given unknown and by given unknown by the given number
If a different unknown is given, a MultyPolynomial will be returned
"""
def integral_n(self, *unknown:str, **kwargs:int) -> Self|MultyPolinomial:
if all(u == self._unkn for u in unknown|kwargs.keys()):
s = self.copy()
for _ in range(len(unknown)+kwargs.get(self._unkn,0)):
s.integral_ip()
return s
return self.toMulty().integral_n(*unknown, **kwargs)
@overload
def integral_n_ip(self, *unknown:str) -> None:
"""
it makes sequentially all the integrations in the given unknown
If a different unknown is given, a MultyPolynomial will be returned
"""
@overload
def integral_n_ip(self, **kwargs:int) -> None:
"""
it makes sequentially all the integrations in the given unknown by the given number
If a different unknown is given, a MultyPolynomial will be returned
"""
@overload
def integral_n_ip(self, *unknown:str, **kwargs:int) -> None:
"""
it makes sequentially all the integrations in the given unknown and by given unknown by the given number
If a different unknown is given, a MultyPolynomial will be returned
"""
def integral_n_ip(self, *unknown:str, **kwargs:int) -> None:
if all(u == self._unkn for u in unknown|kwargs.keys()):
for _ in range(len(unknown)+kwargs.get(self._unkn,0)):
self.integral_ip()
return
raise ValueError(f"the given unknowns {unknown|kwargs.keys()} doesn't match up with {self._unkn}. Consider convert this SinglePolynomial to MultyPolynomial before")
def integralAB(self, a:Number, b:Number) -> Self:
"""
It integrates the MultyPolinomial in the given unknown in the [a,b] interval
"""
if a>b:
raise ValueError(f"'b':({b}) has to be greater than 'a':({a})")
t = self.integral()
return t.evaluate(b)-t.evaluate(a)
def integralAB_ip(self, a:Number, b:Number) -> None:
"""
It integrates the MultyPolinomial in the given unknown in the [a,b] interval
"""
if a>b:
raise ValueError(f"'b':({b}) has to be greater than 'a':({a})")
self.integral_ip()
t= self.copy()
self.evaluate_ip(b)
self-=t.evaluate(a)
def integralAB_n(self, **kwargs:tuple[tuple[int,int],...]) -> Self|MultyPolinomial:
"""
it makes sequentially all the integrations in the given unknown in its respective interval
If a different unknown is given, a MultyPolynomial will be returned
"""
if all(u == self._unkn for u in kwargs.keys()):
t = self.copy()
for unk, intervals in kwargs.items():
for interval in intervals:
t.integralAB_ip(unk, *interval)
return t
return self.toMulty().integralAB_n(**kwargs)
def integralAB_n_ip(self, **kwargs:tuple[tuple[int,int],...]) -> None:
"""
it makes sequentially all the integrations in the given unknown in its respective interval
"""
if all(u == self._unkn for u in kwargs.keys()):
for unk, intervals in kwargs.items():
for interval in intervals:
self.integralAB_ip(unk, *interval)
return
raise ValueError(f"the given unknowns {kwargs.keys()} doesn't match up with {self._unkn}. Consider convert this SinglePolynomial to MultyPolynomial before")
## TRASNFORMATIONS ##
def __neg__(self) -> Self:
"""
It returns a new SinglePolynomial with every coef negated
"""
return super().__neg__()
def __pos__(self) -> Self:
"""
It returns a new SinglePolynomial
"""
return super().__pos__()
def __abs__(self) -> Self:
"""
It returns a new SinglePolynomial with every coef positive
"""
return super().__abs__()
@overload
def __round__(self) -> Self:
"""
It returns a new SinglePolynomial with each coef rounded to the closer integer
"""
@overload
def __round__(self, __n:int|None = None) -> Self:
"""
It returns a new SinglePolynomial with each coef in the given position
"""
def __round__(self, __n:int|None = None) -> Self:
return super().__round__(__n)
def __floor__(self) -> Self:
"It returns the SinglePolynomial with all the coefs floored"
return super().__floor__()
def __ceil__(self) -> Self:
"It returns the SinglePolynomial with all the coefs ceiled"
return super().__ceil__()
def clear(self) -> None:
"""
It transform itself to zero
"""
self._pcoef.clear()
self._pcoef[0]=0
self._icoef.clear()
def clean(self) -> Self:
"""
It returns a new SinglePolynomial removing any unkown wich isn't used. It skips any zero coef
"""
p = {power:coef for power,coef in self._pcoef.items() if coef}
return self.__class__(p if p else {0:0},self._unkn,{power:coef.copy() for power,coef in self._icoef.items() if coef[1]})
def clean_ip(self) -> None:
"""
It updates this SinglePolynomial by removing any unkown wich isn't used. It removes any zero coef
"""
for power,coef in self._pcoef.items():
if not coef:
del self._pcoef[power]
if not self._pcoef:
self._pcoef[0]=0
for power,coef in self._icoef.items():
if not coef[1]:
del self._icoef[power]
@overload
def copy(self) -> Self:
"""
It creates a copy of the current SinglePolynomial
"""
@overload
def copy(self, __ignore:bool=False) -> Self:
"""
It creates a copy of the current SinglePolynomial
if __ignore is True, the Integrals part will be ignored
"""
def copy(self, __ignore:bool = False) -> Self:
return super().copy(__ignore)
@overload
def translate(self, *args:Number) -> Self|MultyPolinomial:
"by giving a number, one and only one, is possible to translate 'vertically' the polymoial"
@overload
def translate(self, **kwargs:Number) -> Self|MultyPolinomial:
"""
for each given unknown, it translates the polynomial by the corrispective value.
If a different unknown is given, a MultyPolynomial will be returned
"""
@overload
def translate(self, *args:Number, **kwargs:Number) -> Self|MultyPolinomial:
"""
By giving a number, in args one and only one, is possible to translate 'vertically' the polymoial.
For each given unknown in kwargs, it translates the polynomial by its corrispective value.
If a different unknown is given, a MultyPolynomial will be returned
"""
def translate(self, *args:Number, **kwargs:Number) -> Self|MultyPolinomial:
if all(u == self._unkn for u in kwargs.keys()):
if kwargs:
p = self.zero(self._unkn)
s = self.__class__({1:1,0:-kwargs.get(self._unkn,0)},self._unkn)
trans = lambda power: s**power
for power,coef in self._pcoef.items():
p+=trans(power)*coef
s._icoef.update({1:['',1],0:['',1]})
s._pcoef.clear()
for power in self._icoef:
p+=trans(power)
for i,coef in enumerate(p._icoef.values()):
coef[0] = f'C{i}'
return p+sum(args)
return self+sum(args)
return self.toMulty().translate(*args, **kwargs)
@overload
def translate_ip(self, *args:Number) -> None:
"by giving a number, one and only one, is possible to translate 'vertically' the polymoial"
@overload