-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy patharithmetic.py
1038 lines (842 loc) · 30.1 KB
/
arithmetic.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
# -*- coding: utf-8 -*-
"""
Mathematical Functions
Basic arithmetic functions, including complex number arithmetic.
"""
from typing import Optional
import sympy
from mathics.builtin.base import (
Builtin,
IterationFunction,
MPMathFunction,
Predefined,
SympyFunction,
SympyObject,
Test,
)
from mathics.builtin.inference import get_assumptions_list
from mathics.builtin.numeric import Abs
from mathics.builtin.scoping import dynamic_scoping
from mathics.core.atoms import (
MATHICS3_COMPLEX_I,
MATHICS3_COMPLEX_I_NEG,
Complex,
Integer,
Integer0,
Integer1,
IntegerM1,
Rational,
Real,
String,
)
from mathics.core.attributes import (
A_HOLD_REST,
A_LISTABLE,
A_NO_ATTRIBUTES,
A_NUMERIC_FUNCTION,
A_PROTECTED,
)
from mathics.core.convert.sympy import SympyExpression, from_sympy, sympy_symbol_prefix
from mathics.core.element import BaseElement
from mathics.core.evaluation import Evaluation
from mathics.core.expression import Expression
from mathics.core.expression_predefined import (
MATHICS3_COMPLEX_INFINITY,
MATHICS3_I_INFINITY,
MATHICS3_I_NEG_INFINITY,
MATHICS3_INFINITY,
MATHICS3_NEG_INFINITY,
PredefinedExpression,
)
from mathics.core.list import ListExpression
from mathics.core.symbols import (
Atom,
Symbol,
SymbolFalse,
SymbolList,
SymbolPlus,
SymbolTimes,
SymbolTrue,
)
from mathics.core.systemsymbols import (
SymbolAnd,
SymbolDirectedInfinity,
SymbolInfix,
SymbolPossibleZeroQ,
SymbolTable,
SymbolUndefined,
)
from mathics.eval.arithmetic import eval_Sign
from mathics.eval.nevaluator import eval_N
# This tells documentation how to sort this module
sort_order = "mathics.builtin.mathematical-functions"
map_direction_infinity = {
Integer1: MATHICS3_INFINITY,
IntegerM1: MATHICS3_NEG_INFINITY,
MATHICS3_COMPLEX_I: MATHICS3_I_INFINITY,
MATHICS3_COMPLEX_I_NEG: MATHICS3_I_NEG_INFINITY,
}
def create_infix(items, operator, prec, grouping):
if len(items) == 1:
return items[0]
else:
return Expression(
SymbolInfix,
ListExpression(*items),
String(operator),
Integer(prec),
Symbol(grouping),
)
class Arg(MPMathFunction):
"""
<url>:Argument (complex analysis):
https://en.wikipedia.org/wiki/Argument_(complex_analysis)</url> (<url>
:WMA link:https://reference.wolfram.com/language/ref/Arg.html</url>)
<dl>
<dt>'Arg'[$z$, $method_option$]
<dd>returns the argument of a complex value $z$.
</dl>
<ul>
<li>'Arg'[$z$] is left unevaluated if $z$ is not a numeric quantity.
<li>'Arg'[$z$] gives the phase angle of $z$ in radians.
<li>The result from 'Arg'[$z$] is always between -Pi and +Pi.
<li>'Arg'[$z$] has a branch cut discontinuity in the complex $z$ plane running \
from -Infinity to 0.
<li>'Arg'[0] is 0.
</ul>
>> Arg[-3]
= Pi
Same as above using sympy's method:
>> Arg[-3, Method->"sympy"]
= Pi
>> Arg[1-I]
= -Pi / 4
Arg evaluate the direction of DirectedInfinity quantities by
the Arg of they arguments:
>> Arg[DirectedInfinity[1+I]]
= Pi / 4
>> Arg[DirectedInfinity[]]
= 1
Arg for 0 is assumed to be 0:
>> Arg[0]
= 0
"""
summary_text = "phase of a complex number"
rules = {
"Arg[0]": "0",
"Arg[DirectedInfinity[]]": "1",
"Arg[DirectedInfinity[a_]]": "Arg[a]",
}
attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_PROTECTED
options = {"Method": "Automatic"}
numpy_name = "angle" # for later
mpmath_name = "arg"
sympy_name = "arg"
def eval(self, z, evaluation, options={}):
"Arg[z_, OptionsPattern[Arg]]"
if Expression(SymbolPossibleZeroQ, z).evaluate(evaluation) is SymbolTrue:
return Integer0
preference = self.get_option(options, "Method", evaluation).get_string_value()
if preference is None or preference == "Automatic":
return super(Arg, self).eval(z, evaluation)
elif preference == "mpmath":
return MPMathFunction.eval(self, z, evaluation)
elif preference == "sympy":
return SympyFunction.eval(self, z, evaluation)
# TODO: add NumpyFunction
evaluation.message(
"meth", f'Arg Method {preference} not in ("sympy", "mpmath")'
)
return
class Assuming(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Assuming.html</url>
<dl>
<dt>'Assuming[$cond$, $expr$]'
<dd>Evaluates $expr$ assuming the conditions $cond$.
</dl>
>> $Assumptions = { x > 0 }
= {x > 0}
>> Assuming[y>0, ConditionalExpression[y x^2, y>0]//Simplify]
= x ^ 2 y
>> Assuming[Not[y>0], ConditionalExpression[y x^2, y>0]//Simplify]
= Undefined
>> ConditionalExpression[y x ^ 2, y > 0]//Simplify
= ConditionalExpression[x ^ 2 y, y > 0]
"""
summary_text = "set assumptions during the evaluation"
attributes = A_HOLD_REST | A_PROTECTED
def eval_assuming(self, assumptions, expr, evaluation: Evaluation):
"Assuming[assumptions_, expr_]"
assumptions = assumptions.evaluate(evaluation)
if assumptions is SymbolTrue:
cond = []
elif isinstance(assumptions, Symbol) or not assumptions.has_form("List", None):
cond = [assumptions]
else:
cond = assumptions.elements
cond = tuple(cond) + get_assumptions_list(evaluation)
list_cond = ListExpression(*cond)
# TODO: reduce the list of predicates
return dynamic_scoping(
lambda ev: expr.evaluate(ev), {"System`$Assumptions": list_cond}, evaluation
)
class Assumptions(Predefined):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/$Assumptions.html</url>
<dl>
<dt>'$Assumptions'
<dd>is the default setting for the Assumptions option used in such functions as Simplify, Refine, and Integrate.
</dl>
"""
summary_text = "assumptions used to simplify expressions"
name = "$Assumptions"
attributes = A_NO_ATTRIBUTES
rules = {
"$Assumptions": "True",
}
messages = {
"faas": "Assumptions should not be False.",
"baas": "Bad formed assumption.",
}
class Boole(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Boole.html</url>
<dl>
<dt>'Boole[expr]'
<dd>returns 1 if expr is True and 0 if expr is False.
</dl>
>> Boole[2 == 2]
= 1
>> Boole[7 < 5]
= 0
>> Boole[a == 7]
= Boole[a == 7]
"""
attributes = A_LISTABLE | A_PROTECTED
summary_text = "translate 'True' to 1, and 'False' to 0"
def eval(self, expr, evaluation: Evaluation):
"Boole[expr_]"
if expr is SymbolTrue:
return Integer1
elif expr is SymbolFalse:
return Integer0
return None
class Complex_(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Complex.html</url>
<dl>
<dt>'Complex'
<dd>is the head of complex numbers.
<dt>'Complex[$a$, $b$]'
<dd>constructs the complex number '$a$ + I $b$'.
</dl>
>> Head[2 + 3*I]
= Complex
>> Complex[1, 2/3]
= 1 + 2 I / 3
>> Abs[Complex[3, 4]]
= 5
"""
summary_text = "head for complex numbers"
name = "Complex"
def eval(self, r, i, evaluation: Evaluation):
"Complex[r_?NumberQ, i_?NumberQ]"
if isinstance(r, Complex) or isinstance(i, Complex):
sym_form = r.to_sympy() + sympy.I * i.to_sympy()
r, i = sym_form.simplify().as_real_imag()
r, i = from_sympy(r), from_sympy(i)
return Complex(r, i)
class ConditionalExpression(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/
language/ref/ConditionalExpression.html</url>
<dl>
<dt>'ConditionalExpression[$expr$, $cond$]'
<dd>returns $expr$ if $cond$ evaluates to $True$, $Undefined$ if $cond$ \
evaluates to $False$.
</dl>
>> ConditionalExpression[x^2, True]
= x ^ 2
>> ConditionalExpression[x^2, False]
= Undefined
>> f = ConditionalExpression[x^2, x>0]
= ConditionalExpression[x ^ 2, x > 0]
>> f /. x -> 2
= 4
>> f /. x -> -2
= Undefined
'ConditionalExpression' uses assumptions to evaluate the condition:
>> $Assumptions = x > 0;
>> ConditionalExpression[x ^ 2, x>0]//Simplify
= x ^ 2
>> $Assumptions = True;
# >> ConditionalExpression[ConditionalExpression[s,x>a], x<b]
# = ConditionalExpression[s, And[x>a, x<b]]
"""
summary_text = "expression defined under condition"
sympy_name = "Piecewise"
rules = {
"ConditionalExpression[expr_, True]": "expr",
"ConditionalExpression[expr_, False]": "Undefined",
"ConditionalExpression[ConditionalExpression[expr_, cond1_], cond2_]": "ConditionalExpression[expr, And@@Flatten[{cond1, cond2}]]",
"ConditionalExpression[expr1_, cond_] + expr2_": "ConditionalExpression[expr1+expr2, cond]",
"ConditionalExpression[expr1_, cond_] expr2_": "ConditionalExpression[expr1 expr2, cond]",
"ConditionalExpression[expr1_, cond_]^expr2_": "ConditionalExpression[expr1^expr2, cond]",
"expr1_ ^ ConditionalExpression[expr2_, cond_]": "ConditionalExpression[expr1^expr2, cond]",
}
def eval_generic(self, expr, cond, evaluation: Evaluation):
"ConditionalExpression[expr_, cond_]"
# What we need here is a way to evaluate
# cond as a predicate, using assumptions.
# Let's delegate this to the And (and Or) symbols...
if not isinstance(cond, Atom) and cond._head is SymbolList:
cond = Expression(SymbolAnd, *(cond.elements))
else:
cond = Expression(SymbolAnd, cond)
if cond is None:
return
if cond is SymbolTrue:
return expr
if cond is SymbolFalse:
return SymbolUndefined
return
def to_sympy(self, expr, **kwargs):
elements = expr.elements
if len(elements) != 2:
return
expr, cond = elements
sympy_cond = None
if isinstance(cond, Symbol):
if cond is SymbolTrue:
sympy_cond = True
elif cond is SymbolFalse:
sympy_cond = False
if sympy_cond is None:
sympy_cond = cond.to_sympy(**kwargs)
if not (sympy_cond.is_Relational or sympy_cond.is_Boolean):
return
sympy_cases = (
(expr.to_sympy(**kwargs), sympy_cond),
(sympy.Symbol(sympy_symbol_prefix + "System`Undefined"), True),
)
return sympy.Piecewise(*sympy_cases)
class Conjugate(MPMathFunction):
"""
<url>:Complex Conjugate:
https://en.wikipedia.org/wiki/Complex_conjugate</url> \
(<url>:WMA:https://reference.wolfram.com/language/ref/Conjugate.html</url>)
<dl>
<dt>'Conjugate[$z$]'
<dd>returns the complex conjugate of the complex number $z$.
</dl>
>> Conjugate[3 + 4 I]
= 3 - 4 I
>> Conjugate[3]
= 3
>> Conjugate[a + b * I]
= Conjugate[a] - I Conjugate[b]
>> Conjugate[{{1, 2 + I 4, a + I b}, {I}}]
= {{1, 2 - 4 I, Conjugate[a] - I Conjugate[b]}, {-I}}
>> Conjugate[1.5 + 2.5 I]
= 1.5 - 2.5 I
"""
mpmath_name = "conj"
rules = {
"Conjugate[Undefined]": "Undefined",
}
summary_text = "complex conjugation"
class DirectedInfinity(SympyFunction):
"""
<url>:WMA link:
https://reference.wolfram.com/language/ref/DirectedInfinity.html</url>
<dl>
<dt>'DirectedInfinity[$z$]'
<dd>represents an infinite multiple of the complex number $z$.
<dt>'DirectedInfinity[]'
<dd>is the same as 'ComplexInfinity'.
</dl>
>> DirectedInfinity[1]
= Infinity
>> DirectedInfinity[]
= ComplexInfinity
>> DirectedInfinity[1 + I]
= (1 / 2 + I / 2) Sqrt[2] Infinity
>> 1 / DirectedInfinity[1 + I]
= 0
>> DirectedInfinity[1] + DirectedInfinity[-1]
: Indeterminate expression -Infinity + Infinity encountered.
= Indeterminate
>> DirectedInfinity[0]
= ComplexInfinity
"""
summary_text = "infinite quantity with a defined direction in the complex plane"
rules = {
"DirectedInfinity[args___] ^ -1": "0",
# Special arguments:
"DirectedInfinity[DirectedInfinity[args___]]": "DirectedInfinity[args]",
"DirectedInfinity[Indeterminate]": "Indeterminate",
"DirectedInfinity[Alternatives[0, 0.]]": "DirectedInfinity[]",
# Plus
"DirectedInfinity[a_] + DirectedInfinity[b_] /; b == -a": (
"Message[Infinity::indet,"
" Unevaluated[DirectedInfinity[a] + DirectedInfinity[b]]];"
"Indeterminate"
),
"DirectedInfinity[] + DirectedInfinity[args___]": (
"Message[Infinity::indet,"
" Unevaluated[DirectedInfinity[] + DirectedInfinity[args]]];"
"Indeterminate"
),
"DirectedInfinity[args___] + _?NumberQ": "DirectedInfinity[args]",
# Times. See if can be reinstalled in eval_Times
"Alternatives[0, 0.] DirectedInfinity[z___]": (
"Message[Infinity::indet,"
" Unevaluated[0 DirectedInfinity[z]]];"
"Indeterminate"
),
"a_?NumericQ * DirectedInfinity[b_]": "DirectedInfinity[a * b]",
"a_ DirectedInfinity[]": "DirectedInfinity[]",
"DirectedInfinity[a_] * DirectedInfinity[b_]": "DirectedInfinity[a * b]",
}
formats = {
"DirectedInfinity[1]": "HoldForm[Infinity]",
"DirectedInfinity[-1]": "HoldForm[Minus[Infinity]]",
"DirectedInfinity[-I]": "HoldForm[Minus[Infinity] I]",
"DirectedInfinity[]": "HoldForm[ComplexInfinity]",
"DirectedInfinity[DirectedInfinity[z_]]": "DirectedInfinity[z]",
"DirectedInfinity[z_?NumericQ]": "HoldForm[z Infinity]",
}
def eval_complex_infinity(self, evaluation: Evaluation):
"""DirectedInfinity[]"""
return MATHICS3_COMPLEX_INFINITY
def eval_directed_infinity(self, direction, evaluation: Evaluation):
"""DirectedInfinity[direction_]"""
result = map_direction_infinity.get(direction, None)
if result:
return result
if direction.is_zero:
return MATHICS3_COMPLEX_INFINITY
normalized_direction = eval_Sign(direction)
# TODO: improve eval_Sign, to avoid the need of the
# following block:
# ############################################
if normalized_direction is None:
ndir = eval_N(direction, evaluation)
if isinstance(ndir, (Integer, Rational, Real)):
if abs(ndir.value) == 1.0:
normalized_direction = direction
else:
normalized_direction = direction / Abs(direction)
elif isinstance(ndir, Complex):
re, im = ndir.value
if abs(re.value**2 + im.value**2 - 1.0) < 1.0e-9:
normalized_direction = direction
else:
normalized_direction = direction / Abs(direction)
else:
return None
# ##############################################
if normalized_direction is None:
return None
return PredefinedExpression(
SymbolDirectedInfinity,
normalized_direction.evaluate(evaluation),
)
def to_sympy(self, expr, **kwargs):
if len(expr.elements) == 1:
dir = expr.elements[0].get_int_value()
if dir == 1:
return sympy.oo
elif dir == -1:
return -sympy.oo
else:
return sympy.Mul((expr.elements[0].to_sympy()), sympy.zoo)
else:
return sympy.zoo
class Element(Builtin):
"""
<url>:Element of:https://en.wikipedia.org/wiki/Element_(mathematics)</url> \
(<url>:WMA:https://reference.wolfram.com/language/ref/Element.html</url>)
<dl>
<dt>'Element[$expr$, $domain$]'
<dd>returns $True$ if $expr$ is an element of $domain$
<dt>'Element[$expr_1$|$expr_2$|..., $domain$]'
<dd>returns $True$ if all the $expr_i$ belongs to $domain$, and \
$False$ if one of the items doesn't.
</dl>
Check if $3$ and $a$ are both integers. If $a$ is not defined, then \
'Element' reduces the condition:
>> Element[3 | a, Integers]
= Element[a, Integers]
Notice that standard domain names ('Primes', 'Integers', 'Rationals', \
'Algebraics', 'Reals', 'Complexes', and 'Booleans')\
are in plural form. If a singular form is used, a warning is shown:
>> Element[a, Real]
: The second argument Real of Element should be one of: Primes, Integers, \
Rationals, Algebraics, Reals, Complexes, or Booleans.
= Element[a, Real]
"""
messages = {
"bset": (
"The second argument `1` of Element should be one of: "
"Primes, Integers, Rationals, Algebraics, "
"Reals, Complexes, or Booleans."
),
}
summary_text = "check whether belongs the domain"
def eval_wrong_domain(
self, elem: BaseElement, domain: BaseElement, evaluation: Evaluation
):
(
"Element[elem_, domain:(Alternatives["
"Algebraic, Bool, Integer, Prime, Rational, Real, Complex])]"
)
evaluation.message("Element", "bset", domain)
return None
def eval_Element_alternatives(
self, elems: BaseElement, domain: BaseElement, evaluation: Evaluation
) -> Optional[Expression]:
"""Element[elems_Alternatives, domain_]"""
items = elems.elements
unknown = []
for item in items:
item_belongs = Element(item, domain).evaluate(evaluation)
if item_belongs is SymbolTrue:
continue
if item_belongs is SymbolFalse:
return SymbolFalse
unknown.append(item)
if len(unknown) == len(items):
return None
if len(unknown) == 0:
return SymbolTrue
# If some of the items remain unkown, return a reduced expression
return Element(Expression(elems.head, *unknown), domain)
class I_(Predefined, SympyObject):
"""
<url>:Imaginary unit:https://en.wikipedia.org/wiki/Imaginary_unit</url> \
(<url>:WMA:https://reference.wolfram.com/language/ref/I.html</url>)
<dl>
<dt>'I'
<dd>represents the imaginary number 'Sqrt[-1]'.
</dl>
>> I^2
= -1
>> (3+I)*(3-I)
= 10
"""
name = "I"
sympy_name = "I"
sympy_obj = sympy.I
summary_text = "imaginary unit"
python_equivalent = 1j
def is_constant(self) -> bool:
return True
def to_sympy(self, symb, **kwargs):
return self.sympy_obj
def evaluate(self, evaluation: Evaluation):
return Complex(Integer0, Integer1)
class Im(SympyFunction):
"""
<url>
:WMA link:
https://reference.wolfram.com/language/ref/Im.html</url>
<dl>
<dt>'Im[$z$]'
<dd>returns the imaginary component of the complex number $z$.
</dl>
>> Im[3+4I]
= 4
>> Plot[{Sin[a], Im[E^(I a)]}, {a, 0, 2 Pi}]
= -Graphics-
"""
summary_text = "imaginary part"
attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_PROTECTED
def eval_complex(self, number, evaluation: Evaluation):
"Im[number_Complex]"
if isinstance(number, Complex):
return number.imag
def eval_number(self, number, evaluation: Evaluation):
"Im[number_?NumberQ]"
return Integer0
def eval(self, number, evaluation: Evaluation):
"Im[number_]"
return from_sympy(sympy.im(number.to_sympy().expand(complex=True)))
class Integer_(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Integer.html</url>
<dl>
<dt>'Integer'
<dd>is the head of integers.
</dl>
>> Head[5]
= Integer
"""
summary_text = "head for integer numbers"
name = "Integer"
class Product(IterationFunction, SympyFunction):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Product.html</url>
<dl>
<dt>'Product[$expr$, {$i$, $imin$, $imax$}]'
<dd>evaluates the discrete product of $expr$ with $i$ ranging from $imin$ to $imax$.
<dt>'Product[$expr$, {$i$, $imax$}]'
<dd>same as 'Product[$expr$, {$i$, 1, $imax$}]'.
<dt>'Product[$expr$, {$i$, $imin$, $imax$, $di$}]'
<dd>$i$ ranges from $imin$ to $imax$ in steps of $di$.
<dt>'Product[$expr$, {$i$, $imin$, $imax$}, {$j$, $jmin$, $jmax$}, ...]'
<dd>evaluates $expr$ as a multiple product, with {$i$, ...}, {$j$, ...}, ... being in outermost-to-innermost order.
</dl>
>> Product[k, {k, 1, 10}]
= 3628800
>> 10!
= 3628800
>> Product[x^k, {k, 2, 20, 2}]
= x ^ 110
>> Product[2 ^ i, {i, 1, n}]
= 2 ^ (n / 2 + n ^ 2 / 2)
>> Product[f[i], {i, 1, 7}]
= f[1] f[2] f[3] f[4] f[5] f[6] f[7]
Symbolic products involving the factorial are evaluated:
>> Product[k, {k, 3, n}]
= n! / 2
Evaluate the $n$th primorial:
>> primorial[0] = 1;
>> primorial[n_Integer] := Product[Prime[k], {k, 1, n}];
>> primorial[12]
= 7420738134810
"""
summary_text = "discrete product"
throw_iterb = False
sympy_name = "Product"
rules = IterationFunction.rules.copy()
rules.update(
{
"MakeBoxes[Product[f_, {i_, a_, b_, 1}],"
" form:StandardForm|TraditionalForm]": (
r'RowBox[{SubsuperscriptBox["\\[Product]",'
r' RowBox[{MakeBoxes[i, form], "=", MakeBoxes[a, form]}],'
r" MakeBoxes[b, form]], MakeBoxes[f, form]}]"
),
}
)
def get_result(self, items):
return Expression(SymbolTimes, *items)
def to_sympy(self, expr, **kwargs):
if expr.has_form("Product", 2) and expr.elements[1].has_form("List", 3):
index = expr.elements[1]
try:
e_kwargs = kwargs.copy()
e_kwargs["convert_all_global_functions"] = True
e = expr.elements[0].to_sympy(**e_kwargs)
i = index.elements[0].to_sympy(**kwargs)
start = index.elements[1].to_sympy(**kwargs)
stop = index.elements[2].to_sympy(**kwargs)
return sympy.product(e, (i, start, stop))
except ZeroDivisionError:
pass
class Rational_(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Rational.html</url>
<dl>
<dt>'Rational'
<dd>is the head of rational numbers.
<dt>'Rational[$a$, $b$]'
<dd>constructs the rational number $a$ / $b$.
</dl>
>> Head[1/2]
= Rational
>> Rational[1, 2]
= 1 / 2
"""
summary_text = "head for rational numbers"
name = "Rational"
def eval(self, n: Integer, m: Integer, evaluation: Evaluation):
"Rational[n_Integer, m_Integer]"
if m.value == 1:
return n
else:
return Rational(n.value, m.value)
class Re(SympyFunction):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Re.html</url>
<dl>
<dt>'Re[$z$]'
<dd>returns the real component of the complex number $z$.
</dl>
>> Re[3+4I]
= 3
>> Plot[{Cos[a], Re[E^(I a)]}, {a, 0, 2 Pi}]
= -Graphics-
"""
summary_text = "real part"
attributes = A_LISTABLE | A_NUMERIC_FUNCTION | A_PROTECTED
sympy_name = "re"
def eval_complex(self, number, evaluation: Evaluation):
"Re[number_Complex]"
if isinstance(number, Complex):
return number.real
def eval_number(self, number, evaluation: Evaluation):
"Re[number_?NumberQ]"
return number
def eval(self, number, evaluation: Evaluation):
"Re[number_]"
return from_sympy(sympy.re(number.to_sympy().expand(complex=True)))
class Real_(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Real.html</url>
<dl>
<dt>'Real'
<dd>is the head of real (inexact) numbers.
</dl>
>> x = 3. ^ -20;
>> InputForm[x]
= 2.8679719907924413*^-10
>> Head[x]
= Real
"""
summary_text = "head for real numbers"
name = "Real"
class RealNumberQ(Test):
"""
## Not found in WMA
## <url>:WMA link:https://reference.wolfram.com/language/ref/RealNumberQ.html</url>
<dl>
<dt>'RealNumberQ[$expr$]'
<dd>returns 'True' if $expr$ is an explicit number with no imaginary component.
</dl>
>> RealNumberQ[10]
= True
>> RealNumberQ[4.0]
= True
>> RealNumberQ[1+I]
= False
>> RealNumberQ[0 * I]
= True
>> RealNumberQ[0.0 * I]
= False
"""
attributes = A_NO_ATTRIBUTES
summary_text = "test whether an expression is a real number"
def test(self, expr) -> bool:
return isinstance(expr, (Integer, Rational, Real))
class Sum(IterationFunction, SympyFunction):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Sum.html</url>
<dl>
<dt>'Sum[$expr$, {$i$, $imin$, $imax$}]'
<dd>evaluates the discrete sum of $expr$ with $i$ ranging from $imin$ to $imax$.
<dt>'Sum[$expr$, {$i$, $imax$}]'
<dd>same as 'Sum[$expr$, {$i$, 1, $imax$}]'.
<dt>'Sum[$expr$, {$i$, $imin$, $imax$, $di$}]'
<dd>$i$ ranges from $imin$ to $imax$ in steps of $di$.
<dt>'Sum[$expr$, {$i$, $imin$, $imax$}, {$j$, $jmin$, $jmax$}, ...]'
<dd>evaluates $expr$ as a multiple sum, with {$i$, ...}, {$j$, ...}, ... being \
in outermost-to-innermost order.
</dl>
A sum that Gauss in elementary school was asked to do to kill time:
>> Sum[k, {k, 1, 10}]
= 55
The symbolic form he used:
>> Sum[k, {k, 1, n}]
= n (1 + n) / 2
A Geometric series with a finite limit:
>> Sum[1 / 2 ^ i, {i, 1, k}]
= 1 - 2 ^ (-k)
A Geometric series using Infinity:
>> Sum[1 / 2 ^ i, {i, 1, Infinity}]
= 1
Leibniz formula used in computing Pi:
>> Sum[1 / ((-1)^k (2k + 1)), {k, 0, Infinity}]
= Pi / 4
A table of double sums to compute squares:
>> Table[ Sum[i * j, {i, 0, n}, {j, 0, n}], {n, 0, 4} ]
= {0, 1, 9, 36, 100}
Computing Harmonic using a sum
>> Sum[1 / k ^ 2, {k, 1, n}]
= HarmonicNumber[n, 2]
Other symbolic sums:
>> Sum[k, {k, n, 2 n}]
= 3 n (1 + n) / 2
A sum with Complex-number iteration values
>> Sum[k, {k, I, I + 1}]
= 1 + 2 I
>> Sum[k, {k, Range[5]}]
= 15
>> Sum[f[i], {i, 1, 7}]
= f[1] + f[2] + f[3] + f[4] + f[5] + f[6] + f[7]
Verify algebraic identities:
>> Sum[x ^ 2, {x, 1, y}] - y * (y + 1) * (2 * y + 1) / 6
= 0
## Issue #302
## The sum should not converge since the first term is 1/0.
#> Sum[i / Log[i], {i, 1, Infinity}]
= Sum[i / Log[i], {i, 1, Infinity}]
#> Sum[Cos[Pi i], {i, 1, Infinity}]
= Sum[Cos[i Pi], {i, 1, Infinity}]
"""
summary_text = "discrete sum"
# Do not throw warning message for symbolic iteration bounds
throw_iterb = False
sympy_name = "Sum"
rules = IterationFunction.rules.copy()
rules.update(
{
"MakeBoxes[Sum[f_, {i_, a_, b_, 1}],"
" form:StandardForm|TraditionalForm]": (
r'RowBox[{SubsuperscriptBox["\\[Sum]",'
r' RowBox[{MakeBoxes[i, form], "=", MakeBoxes[a, form]}],'
r" MakeBoxes[b, form]], MakeBoxes[f, form]}]"
),
}
)
def get_result(self, items):
return Expression(SymbolPlus, *items)
def to_sympy(self, expr, **kwargs) -> Optional[SympyExpression]:
"""
Perform summation via sympy.summation
"""
if expr.has_form("Sum", 2) and expr.elements[1].has_form("List", 3):
index = expr.elements[1]
arg_kwargs = kwargs.copy()
arg_kwargs["convert_all_global_functions"] = True
f_sympy = expr.elements[0].to_sympy(**arg_kwargs)
if f_sympy is None:
return
evaluation = kwargs.get("evaluation", None)
# Handle summation parameters: variable, min, max