forked from charcoal-lang/Charcoal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wolfram.py
2917 lines (2616 loc) · 98 KB
/
wolfram.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 math import (
exp, log, log2, log10, sqrt, sin, cos, tan, asin, acos, atan, floor, ceil,
isinf
)
from functools import reduce, lru_cache
import unicodedata as ud
try:
from regex import (
match, search, split, sub as re_sub, findall, finditer,
compile as re_compile, escape as re_escape,
M as multiline_flag
)
def multilineify(function):
def wrap_function(*args, **kwargs):
kwargs['flags'] = multiline_flag
return function(*args, **kwargs)
return wrap_function
match, search, split, re_sub, findall, finditer = (
multilineify(match),
multilineify(search),
multilineify(split),
multilineify(re_sub),
multilineify(findall),
multilineify(finditer)
)
except Exception as e:
print("Please install the 'regex' module: 'sudo -H pip3 install regex'")
__import__("sys").exit()
# TODO: chain plus/minus for less precision needed
# TODO: tests for rational ops
# TODO: feature parity for stringsplit, stringreplace and stringcases
# TODO: handle infinite precision in arithmetic
# TODO: complex
# TODO: get literal for number creation whenever possible
# TODO: not infinite precision Rational * and /
generator = type(i for i in [])
r_whitespace = re_compile(r"\s+")
prime_cache = [2, 3]
def take(generator, n):
if n:
for _ in range(n):
try:
yield next(generator)
except:
break
else:
while True:
try:
yield next(generator)
except:
break
def prime_gen():
global prime_cache
for number in prime_cache:
yield number
n = prime_cache[-1]
while True:
if all(n % number for number in prime_cache):
prime_cache += [n]
yield n
n += 2
def flatten(iterable):
return [item for element in iterable for item in (
flatten(element)
if hasattr(element, "__iter__") and not isinstance(element, str) else
[element]
)]
def remove_diacritics(string):
return ''.join(
(c for c in ud.normalize("NFD", string) if ud.category(c) != "Mn")
)
rd = remove_diacritics
heads = []
headifies = []
def headify(cls):
global heads
global headifies
if cls not in heads:
heads += [cls]
def fn(leaves, precision=None):
return cls(*leaves)
headifies += [fn]
return fn
return headifies[heads.index(cls)]
def create_expression(value):
value_type = type(value)
if value is None:
return None
elif callable(value):
return value
elif isinstance(value, Expression):
return value
elif value_type == complex:
return Complex(value)
elif value_type == str:
return String(value)
elif value_type == list or value_type == tuple or value_type == generator:
return List(*[create_expression(item) for item in value])
elif value_type != int and value % 1:
value = round(value, 15)
exponent = 0
while value % 1:
value *= 10
exponent -= 1
return Real(int(value), exponent, float("inf"))
else:
exponent = 0
if value:
while not value % 10:
value //= 10
exponent += 1
return Integer(value, exponent)
cx = create_expression
def boolean(value):
return _True if value else _False
def simplify(left, right, fn, repeat=False):
if type(left) == Expression:
left = left.run()
if type(right) == Expression:
right = right.run()
if isinstance(left, List):
if isinstance(right, List):
if len(left.leaves) != len(right.leaves):
raise Exception("Lists have different length")
return SymbolicList(
*(simplify(l, r, fn, True) for l, r in zip(left, right))
)
return SymbolicList(*(simplify(l, right, fn, True) for l in left))
if isinstance(right, List):
return SymbolicList(*(simplify(left, r, fn, True) for r in right))
if repeat:
return fn(left, right)
def simplify_multiple(items, fn):
items = list(items)
i, l = 0, len(items) - 1
while i < l:
simple = simplify(items[i], items[i + 1], fn)
if simple and isinstance(simple, List):
items[:2] = [SymbolicOperation(add, *simple.leaves)]
l -= 1
else:
i += 1
return items
class Operation(object):
__slots__ = ("symbol", "precedence", "commutative", "simplify", "function")
def __init__(self, symbol, precedence, commutative, simplify, function):
self.symbol = symbol
self.precedence = precedence
self.commutative = commutative
self.simplify = lambda items: simplify(
simplify_multiple(items, function)
)
self.function = function
def _pow_simplify(items):
if len(items) == 1:
return items
if items[0] == One or items[1] == One:
return (items[0],)
if items[1] == Zero:
return (One,)
return items
pow = Operation("^", 4, False, _pow_simplify, lambda l, r: l ** r)
def _mul_simplify(items):
if any(item == Zero for item in items):
return (Zero,)
return list(sorted(filter(lambda item: item != One, items)))
mul = Operation("", 3, True, _mul_simplify, lambda l, r: l * r)
def _div_simplify(items):
if items[0] == Zero:
return (Zero,)
if len(items) == 1:
return items
if items[1] == One:
return (items[0],)
return items
div = Operation("/", 3, False, _div_simplify, lambda l, r: l / r)
def _add_simplify(items):
return list(sorted(filter(lambda item: item != Zero, items)))
add = Operation("+", 2, True, _add_simplify, lambda l, r: l + r)
def _sub_simplify(items):
if items[0] == Zero:
if len(items) == 1:
return items
return (items[1],)
if items[1] == Zero:
return (items[0],)
return items
sub = Operation("-", 2, False, _sub_simplify, lambda l, r: l - r)
def is_exactly_int(item, numeral, value, exponent):
if isinstance(item, int):
if item == numeral:
return True
elif (
isinstance(item, Integer) and
item.leaves[1] == exponent and
item.leaves[0] == value
):
return True
return False
class Comparable(object):
def cmp(self, other):
pass
def __eq__(self, other):
return self.cmp(other) == 0
def __lt__(self, other):
return self.cmp(other) == -1
def __gt__(self, other):
return self.cmp(other) == 1
def __ne__(self, other):
return self.cmp(other) != 0
def __le__(self, other):
return self.cmp(other) < 1
def __ge__(self, other):
return self.cmp(other) > -1
class Expression(object):
__slots__ = ("head", "leaves", "run", "op")
def __init__(
self, head=None, leaves=[], run=None, op=None
):
self.head = head
self.leaves = [create_expression(leaf) for leaf in leaves]
self.run = run or (lambda precision=None: self.head(
self.leaves, precision
))
self.op = op
def __add__(self, other):
if is_exactly_int(other, 0, 0, 0):
return self
if is_exactly_int(self, 0, 0, 0):
return other
if (
isinstance(self, Symbolic) or
isinstance(other, Symbolic)
):
return SymbolicOperation(add, self, other)
return Expression(
None, [],
lambda precision=10: self.run(precision + 2) + (
create_expression(other).run(precision + 2)
)
)
def __radd__(self, other):
return Expression.__add__(other, self)
def __sub__(self, other):
if is_exactly_int(other, 0, 0, 0):
return self
if (
isinstance(self, Symbolic) or
isinstance(other, Symbolic)
):
return SymbolicOperation(sub, self, other)
return Expression(
None, [],
lambda precision=10: self.run(precision + 2) - (
create_expression(other).run(precision + 2)
)
)
def __rsub__(self, other):
if is_exactly_int(self, 0, 0, 0):
return other
if (
isinstance(self, Symbolic) or
isinstance(other, Symbolic)
):
return SymbolicOperation(sub, other, self)
return Expression(
None, [],
lambda precision=10: (
create_expression(other).run(precision + 2)
) - self.run(precision + 2)
)
def __mul__(self, other):
if is_exactly_int(self, 0, 0, 0) or is_exactly_int(other, 0, 0, 0):
return Integer(0)
if is_exactly_int(self, 1, 1, 0):
return other
if is_exactly_int(other, 1, 1, 0):
return self
if (
isinstance(self, Symbolic) or
isinstance(other, Symbolic)
):
return SymbolicOperation(mul, self, other)
return Expression(
None, [],
lambda precision=10: self.run(precision + 2) * (
create_expression(other).run(precision + 2)
)
)
def __rmul__(self, other):
return Expression.__mul__(other, self)
def __truediv__(self, other):
if is_exactly_int(self, 0, 0, 0):
return Integer(0)
if is_exactly_int(other, 1, 1, 0):
return self
if (
isinstance(self, Symbolic) or
isinstance(other, Symbolic)
):
return SymbolicOperation(div, self, other)
return Expression(
None, [],
lambda precision=10: self.run(precision + 2) / (
create_expression(other).run(precision + 2)
)
)
def __rtruediv__(self, other):
if is_exactly_int(other, 0, 0, 0):
return Integer(0)
if is_exactly_int(self, 1, 1, 0):
return other
if (
isinstance(self, Symbolic) or
isinstance(other, Symbolic)
):
return SymbolicOperation(div, other, self)
return Expression(
None, [],
lambda precision=10: (
create_expression(other).run(precision + 2)
) / self.run(precision + 2)
)
def __pow__(self, other):
if is_exactly_int(other, 0, 0, 0):
return Integer(1)
if is_exactly_int(other, 1, 1, 0):
return self
if is_exactly_int(self, 0, 0, 0):
return Integer(0)
if is_exactly_int(self, 1, 1, 0):
return Integer(1)
if (
isinstance(self, Symbolic) or
isinstance(other, Symbolic)
):
return SymbolicOperation(pow, self, other)
return Expression(
None, [],
lambda precision=10: self.run(precision + 2) ** (
create_expression(other).run(precision + 2)
)
)
def __rpow__(self, other):
if (
isinstance(self, Symbolic) or
isinstance(other, Symbolic)
):
return SymbolicOperation(pow, other, self)
return Expression(
None, [],
lambda precision=10: (
create_expression(other).run(precision + 2)
) ** self.run(precision + 2),
op=pow
)
def __str__(self):
result = self.run()
if type(result) == Expression:
raise Exception("Expression evaluates to Expression")
return str(result)
def to_number(self):
result = self.run()
if type(result) == Expression:
raise Exception("Expression evaluates to Expression")
return result.to_number()
def __int__(self):
return int(self.to_number())
def to_precision(self, precision=None):
return self.run().to_precision(precision)
def is_integer(self):
return self.run().is_integer()
def is_odd(self):
return self.run().is_odd()
def is_even(self):
return self.run().is_even()
class Symbol(Expression):
pass
class Symbolic(Expression):
pass
class SymbolicOperation(Symbolic, Comparable):
__slots__ = ("op",)
def __new__(cls, op, *items):
i, l = 0, len(items)
items = list(items)
if op.commutative:
while i < l:
if (
isinstance(items[i], SymbolicOperation) and
items[i].op.symbol == op.symbol
):
delta = len(items[i].items)
l += delta - 1
items[i:i + 1] = items[i].items
else:
i += 1
simple = op.simplify(items)
if len(simple) == 1:
return simple[0]
return super().__new__(cls)
def __init__(self, op, *items):
if hasattr(self, "op"):
# Already initialized
return
super().__init__(head=headify(SymbolicOperation))
self.op = op
self.items = items
i, l = 0, len(items)
items = list(items)
while i < l:
if (
op.commutative and
isinstance(items[i], SymbolicOperation) and
items[i].op.symbol == op.symbol
):
delta = len(items[i].items)
l += delta - 1
items[i:i + 1] = items[i].items
else:
i += 1
self.items = op.simplify(items)
if len(self.items) == 1:
raise Exception("wat?")
self.run = lambda precision=10: str(self)
def __str__(self, str=str):
return (
(" " + self.op.symbol + " ") if self.op.symbol else " "
).join(
"(" + str(item) + ")" if (
isinstance(item, Expression) and
item.op and
item.op.precedence < self.op.precedence
) else str(item)
for item in self.items
).replace(" + -", " - ")
def __repr__(self):
return self.__str__(repr)
class SymbolicVariable(Symbolic, Comparable):
__slots__ = ("__name__", "name", "op")
def __init__(self, name):
super().__init__(head=headify(SymbolicVariable))
self.__name__ = name
self.name = name
self.run = lambda precision=10: str(self)
def __str__(self):
return self.name
def __repr__(self):
return ":" + self.name
def __call__(self, leaves):
return SymbolicFunction(self, leaves)
def __add__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__add__(self, other)
def __radd__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__radd__(self, other)
def __sub__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__sub__(self, other)
def __rsub__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__rdub__(self, other)
def __mul__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__mul__(self, other)
def __rmul__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__rmul__(self, other)
def __div__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__div__(self, other)
def __rdiv__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__rdiv__(self, other)
def __pow__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__pow__(self, other)
def __rpow__(self, other):
if not isinstance(other, Expression):
other = create_expression(other)
return Expression.__rpow__(self, other)
def cmp(self, other):
if isinstance(other, Number):
return 1
if isinstance(other, SymbolicVariable):
return (
1 if self.name > other.name else
-1 if self.name < other.name else
0
)
if isinstance(other, SymbolicOperation):
if other.op == mul:
for item in other.items:
if not isinstance(other, Number):
return self.cmp(item)
return self.cmp(other.items[0])
class SymbolicFunction(Symbolic):
__slots__ = ("leaves",)
def __init__(self, head, leaves):
super().__init__(head=headify(head))
self.head = head
self.leaves = leaves
self.run = lambda: self
def __str__(self):
return (
self.head.__name__ + "[" + ", ".join(map(str, self.leaves)) + "]"
)
def __repr__(self):
return str(self)
# Options
IC = IgnoreCase = Symbol()
A = All = Symbol()
O = Overlaps = Symbol()
In = Indeterminate = Symbol()
class Number(Expression):
__slots__ = ("size", "sign")
def __init__(self, head=None):
super().__init__(head=head)
self.size = 0
self.sign = 0
def __eq__(self, other):
if isinstance(other, int):
other = Integer(other)
elif isinstance(other, float):
other = create_expression(other)
if isinstance(other, Number):
if self.sign != other.sign:
return False
if self.size != other.size:
return False
self_rational = isinstance(self, Rational)
other_rational = isinstance(other, Rational)
if isinstance(self, Real) and isinstance(other, Real):
self_i = 1 + self_rational
other_i = 1 + other_rational
min_exponent = min(self.leaves[1], other.leaves[1])
new_self = self.leaves[0] * 10 ** (
self.leaves[self_i] - min_exponent
)
new_other = other.leaves[0] * 10 ** (
other.leaves[other_i] - min_exponent
)
if self_rational:
new_other *= self.leaves[1]
if other_rational:
new_self *= other.leaves[1]
return new_self == new_other
return False
def __gt__(self, other):
if isinstance(other, int):
other = Integer(other)
elif isinstance(other, float):
other = create_expression(other)
if isinstance(other, Number):
if self.sign > other.sign:
return True
if self.sign < other.sign:
return False
if self.size > other.size:
return self.sign == 1
if self.size < other.size:
return self.sign == -1
self_rational = isinstance(self, Rational)
other_rational = isinstance(other, Rational)
if isinstance(self, Real) and isinstance(other, Real):
self_i = 1 + self_rational
other_i = 1 + other_rational
min_exponent = min(self.leaves[1], other.leaves[1])
new_self = self.leaves[0] * 10 ** (
self.leaves[self_i] - min_exponent
)
new_other = other.leaves[0] * 10 ** (
other.leaves[other_i] - min_exponent
)
if self_rational:
new_other *= self.leaves[1]
if other_rational:
new_self *= other.leaves[1]
return new_self > new_other
return False
def __lt__(self, other):
if isinstance(other, int):
other = Integer(other)
elif isinstance(other, float):
other = create_expression(other)
if isinstance(other, Number):
if self.sign < other.sign:
return True
if self.sign > other.sign:
return False
if self.size < other.size:
return self.sign == 1
if self.size > other.size:
return self.sign == -1
self_rational = isinstance(self, Rational)
other_rational = isinstance(other, Rational)
if isinstance(self, Real) and isinstance(other, Real):
self_i = 1 + self_rational
other_i = 1 + other_rational
min_exponent = min(self.leaves[1], other.leaves[1])
new_self = self.leaves[0] * 10 ** (
self.leaves[self_i] - min_exponent
)
new_other = other.leaves[0] * 10 ** (
other.leaves[other_i] - min_exponent
)
if self_rational:
new_other *= self.leaves[1]
if other_rational:
new_self *= other.leaves[1]
return new_self < new_other
return False
def __ne__(self, other):
return not self == other
def __ge__(self, other):
if isinstance(other, int):
other = Integer(other)
elif isinstance(other, float):
other = create_expression(other)
if isinstance(other, Number):
if self.sign > other.sign:
return True
if self.sign < other.sign:
return False
if self.size > other.size:
return self.sign == 1
if self.size < other.size:
return self.sign == -1
self_rational = isinstance(self, Rational)
other_rational = isinstance(other, Rational)
if isinstance(self, Real) and isinstance(other, Real):
self_i = 1 + self_rational
other_i = 1 + other_rational
min_exponent = min(self.leaves[1], other.leaves[1])
new_self = self.leaves[0] * 10 ** (
self.leaves[self_i] - min_exponent
)
new_other = other.leaves[0] * 10 ** (
other.leaves[other_i] - min_exponent
)
if self_rational:
new_other *= self.leaves[1]
if other_rational:
new_self *= other.leaves[1]
return new_self >= new_other
return False
def __le__(self, other):
if isinstance(other, int):
other = Integer(other)
elif isinstance(other, float):
other = create_expression(other)
if isinstance(other, Number):
if self.sign < other.sign:
return True
if self.sign > other.sign:
return False
if self.size < other.size:
return self.sign == 1
if self.size > other.size:
return self.sign == -1
self_rational = isinstance(self, Rational)
other_rational = isinstance(other, Rational)
if isinstance(self, Real) and isinstance(other, Real):
self_i = 1 + self_rational
other_i = 1 + other_rational
min_exponent = min(self.leaves[1], other.leaves[1])
new_self = self.leaves[0] * 10 ** (
self.leaves[self_i] - min_exponent
)
new_other = other.leaves[0] * 10 ** (
other.leaves[other_i] - min_exponent
)
if self_rational:
new_other *= self.leaves[1]
if other_rational:
new_self *= other.leaves[1]
return new_self <= new_other
return False
class Real(Number):
__slots__ = ("is_int", "precision")
def __init__(self, value, exponent=0, precision=0, is_int=False):
super().__init__(head=headify(Real))
self.precision = precision or floor(log10(max(1, abs(value))))
self.is_int = is_int
self.leaves = [value, exponent]
self.size = log10(max(1, value)) + exponent
self.sign = 1 if value > 0 else -1 if value < 0 else 0
def __str__(self):
exponent = self.leaves[1]
string = str(self.leaves[0])
zeroes = 1 - exponent - len(string)
if zeroes > 0:
string = "0" * zeroes + string
return (
string + "0" * exponent
if exponent > 0 else
(string[:exponent] + "." + string[exponent:])
if exponent < 0 else
string
)
def __repr__(self):
return str(self)
def __add__(self, other):
if isinstance(other, Symbolic):
return SymbolicOperation(add, self, other)
if type(other) == Expression:
return other + self
if isinstance(other, Real):
precision = max(0, min(self.precision, other.precision) - 2)
exponent_difference = self.leaves[1] - other.leaves[1]
if exponent_difference > 0:
value = (
self.leaves[0] * 10 ** exponent_difference +
other.leaves[0]
)
else:
value = (
self.leaves[0] +
other.leaves[0] * 10 ** -exponent_difference
)
if isinf(precision):
exponent = min(self.leaves[1], other.leaves[1])
return (Integer if exponent >= 0 else Real)(
value, exponent, precision=precision
)
actual_precision = floor(log10(abs(value) or 1))
return Real(
(
value * 10 ** (precision - actual_precision)
if precision - actual_precision > 1 else
value // 10 ** (actual_precision - precision) + bool(
value < 0 and
value % 10 ** (actual_precision - precision)
)
),
(
min(self.leaves[1], other.leaves[1]) +
actual_precision -
precision
),
precision=precision
)
def __sub__(self, other):
if isinstance(other, Symbolic):
return SymbolicOperation(sub, self, other)
if type(other) == Expression:
return other.__rsub__(self)
if type(other) == Real:
precision = max(0, min(self.precision, other.precision) - 2)
exponent_difference = self.leaves[1] - other.leaves[1]
if exponent_difference > 0:
value = (
self.leaves[0] * 10 ** exponent_difference -
other.leaves[0]
)
else:
value = (
self.leaves[0] -
other.leaves[0] * 10 ** -exponent_difference
)
if isinf(precision):
exponent = min(self.leaves[1], other.leaves[1])
return (Integer if exponent >= 0 else Real)(
value,
min(self.leaves[1], other.leaves[1]),
precision=precision
)
actual_precision = floor(log10(abs(value) or 1))
return Real(
(
value * 10 ** (precision - actual_precision)
if precision - actual_precision > 1 else
value // 10 ** (actual_precision - precision) + bool(
value < 0 and
value % 10 ** (actual_precision - precision)
)
),
(
min(self.leaves[1], other.leaves[1]) +
actual_precision -
precision
),
precision=precision
)
def __mul__(self, other):
if isinstance(other, Symbolic):
return SymbolicOperation(mul, self, other)
if type(other) == Expression:
return other * self
if isinstance(other, Real):
precision = max(0, min(self.precision, other.precision) - 2)
value = self.leaves[0] * other.leaves[0]
actual_precision = floor(log10(abs(value) or 1))
if isinf(precision):
exponent = min(self.leaves[1], other.leaves[1])
return (Integer if exponent >= 0 else Real)(
value,
self.leaves[1] + other.leaves[1],
precision=precision
)
return Real(
(
value * 10 ** (precision - actual_precision)
if precision - actual_precision > 1 else
value // 10 ** (actual_precision - precision) + bool(
value < 0 and
value % 10 ** (actual_precision - precision)
)
),
(
self.leaves[1] +
other.leaves[1] +
actual_precision -
precision
),
precision=precision
)
if type(other) == Rational or type(other) == Complex:
return other * self
return self * Real(other)
def __truediv__(self, other):
if isinstance(other, Symbolic):
return SymbolicOperation(div, self, other)
if type(other) == Expression:
return other.__rtruediv__(self)
if isinstance(other, Real):
# TODO: add precision crap here maybe?
precision = max(0, min(self.precision, other.precision) - 2)
if isinf(precision):
min_exponent = min(self.leaves[1], other.leaves[1])
self.leaves[1] -= min_exponent
other.leaves[1] -= min_exponent
int_self = int(self)
int_other = int(other)
if int_self % int_other:
return Rational(int(self), int(other))
return Integer(int(self) // int(other))
pow10 = 10 ** precision * self.leaves[0]
return Real(
pow10 // other.leaves[0] + bool(
pow10 < 0 and pow10 % other.leaves[0]
),
self.leaves[1] - other.leaves[1] - precision,
precision=precision
)
other_type = type(other)
if other_type == Rational:
return Rational(self.leaves[0], 1, self.leaves[1]) / other
if other_type == Complex:
pass # TODO
def __neg__(self):
return Real(
-self.leaves[0], self.leaves[1], self.precision, self.is_int
)
def __invert__(self):
return Integer(~int(self))
def __abs__(self):
return Real(
abs(self.leaves[0]), self.leaves[1], self.precision, self.is_int
)
def __int__(self):
return int(
self.leaves[0] * 10 ** self.leaves[1]
if self.leaves[1] >= 0 else
self.leaves[0] / 10 ** -self.leaves[1]
)
def __float__(self):
return float(
self.leaves[0] * 10 ** self.leaves[1]
if self.leaves[1] >= 0 else
self.leaves[0] / 10 ** -self.leaves[1]
)
def to_number(self):
result = (
self.leaves[0] * 10 ** self.leaves[1]