-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathcalculus.py
2400 lines (2087 loc) · 80.4 KB
/
calculus.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 -*-
"""
Calculus
Originally called infinitesimal calculus or "the calculus of infinitesimals", \
is the mathematical study of continuous change, in the same way that geometry \
is the study of shape and algebra is the study of generalizations of \
arithmetic operations.
"""
from itertools import product
from typing import Optional
import numpy as np
import sympy
from mathics.algorithm.integrators import (
_fubini,
_internal_adaptative_simpsons_rule,
decompose_domain,
eval_D_to_Integral,
)
from mathics.algorithm.series import (
build_series,
series_derivative,
series_plus_series,
series_times_series,
)
from mathics.builtin.base import Builtin, PostfixOperator, SympyFunction
from mathics.builtin.scoping import dynamic_scoping
from mathics.core.atoms import (
Atom,
Integer,
Integer0,
Integer1,
Integer10,
IntegerM1,
Number,
Rational,
Real,
String,
)
from mathics.core.attributes import (
A_CONSTANT,
A_HOLD_ALL,
A_LISTABLE,
A_N_HOLD_ALL,
A_PROTECTED,
A_READ_PROTECTED,
)
from mathics.core.convert.expression import to_expression, to_mathics_list
from mathics.core.convert.function import expression_to_callable_and_args
from mathics.core.convert.python import from_python
from mathics.core.convert.sympy import SympyExpression, from_sympy, sympy_symbol_prefix
from mathics.core.evaluation import Evaluation
from mathics.core.expression import Expression
from mathics.core.list import ListExpression
from mathics.core.number import MACHINE_EPSILON, dps
from mathics.core.rules import Pattern
from mathics.core.symbols import (
BaseElement,
Symbol,
SymbolFalse,
SymbolList,
SymbolPlus,
SymbolPower,
SymbolTimes,
SymbolTrue,
)
from mathics.core.systemsymbols import (
SymbolAnd,
SymbolAutomatic,
SymbolConditionalExpression,
SymbolD,
SymbolDerivative,
SymbolInfinity,
SymbolInfix,
SymbolIntegrate,
SymbolLeft,
SymbolLog,
SymbolNIntegrate,
SymbolO,
SymbolRule,
SymbolSequence,
SymbolSeries,
SymbolSeriesData,
SymbolSimplify,
SymbolUndefined,
)
from mathics.eval.makeboxes import format_element
from mathics.eval.nevaluator import eval_N
# These should be used in lower-level formatting
SymbolDifferentialD = Symbol("System`DifferentialD")
SymbolIntegral = Symbol("System`Integral")
# Maybe this class should be in a module "mathics.builtin.domains" or something like that
class Complexes(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Complexes.html</url>
<dl>
<dt>'Complexes'
<dd>the domain of complex numbers, as in $x$ in Complexes.
</dl>
"""
summary_text = "the domain complex numbers"
class D(SympyFunction):
"""
<url>:Derivative:https://en.wikipedia.org/wiki/Derivative</url>\
(<url>:WMA:https://reference.wolfram.com/language/ref/D.html</url>)
<dl>
<dt>'D[$f$, $x$]'
<dd>gives the partial derivative of $f$ with respect to $x$.
<dt>'D[$f$, $x$, $y$, ...]'
<dd>differentiates successively with respect to $x$, $y$, etc.
<dt>'D[$f$, {$x$, $n$}]'
<dd>gives the multiple derivative of order $n$.
<dt>'D[$f$, {{$x1$, $x2$, ...}}]'
<dd>gives the vector derivative of $f$ with respect to $x1$, $x2$, etc.
</dl>
First-order derivative of a polynomial:
>> D[x^3 + x^2, x]
= 2 x + 3 x ^ 2
Second-order derivative:
>> D[x^3 + x^2, {x, 2}]
= 2 + 6 x
Trigonometric derivatives:
>> D[Sin[Cos[x]], x]
= -Cos[Cos[x]] Sin[x]
>> D[Sin[x], {x, 2}]
= -Sin[x]
>> D[Cos[t], {t, 2}]
= -Cos[t]
Unknown variables are treated as constant:
>> D[y, x]
= 0
>> D[x, x]
= 1
>> D[x + y, x]
= 1
Derivatives of unknown functions are represented using 'Derivative':
>> D[f[x], x]
= f'[x]
>> D[f[x, x], x]
= Derivative[0, 1][f][x, x] + Derivative[1, 0][f][x, x]
>> D[f[x, x], x] // InputForm
= Derivative[0, 1][f][x, x] + Derivative[1, 0][f][x, x]
Chain rule:
>> D[f[2x+1, 2y, x+y], x]
= 2 Derivative[1, 0, 0][f][1 + 2 x, 2 y, x + y] + Derivative[0, 0, 1][f][1 + 2 x, 2 y, x + y]
>> D[f[x^2, x, 2y], {x,2}, y] // Expand
= 8 x Derivative[1, 1, 1][f][x ^ 2, x, 2 y] + 8 x ^ 2 Derivative[2, 0, 1][f][x ^ 2, x, 2 y] + 2 Derivative[0, 2, 1][f][x ^ 2, x, 2 y] + 4 Derivative[1, 0, 1][f][x ^ 2, x, 2 y]
Compute the gradient vector of a function:
>> D[x ^ 3 * Cos[y], {{x, y}}]
= {3 x ^ 2 Cos[y], -x ^ 3 Sin[y]}
Hesse matrix:
>> D[Sin[x] * Cos[y], {{x,y}, 2}]
= {{-Cos[y] Sin[x], -Cos[x] Sin[y]}, {-Cos[x] Sin[y], -Cos[y] Sin[x]}}
#> D[2/3 Cos[x] - 1/3 x Cos[x] Sin[x] ^ 2,x]//Expand
= -2 x Cos[x] ^ 2 Sin[x] / 3 + x Sin[x] ^ 3 / 3 - 2 Sin[x] / 3 - Cos[x] Sin[x] ^ 2 / 3
#> D[f[#1], {#1,2}]
= f''[#1]
#> D[(#1&)[t],{t,4}]
= 0
#> Attributes[f] ={HoldAll}; Apart[f''[x + x]]
= f''[2 x]
#> Attributes[f] = {}; Apart[f''[x + x]]
= f''[2 x]
## Issue #375
#> D[{#^2}, #]
= {2 #1}
"""
# TODO
"""
>> D[2x, 2x]
= 0
"""
messages = {
"dvar": (
"Multiple derivative specifier `1` does not have the form "
"{variable, n}, where n is a non-negative machine integer."
),
}
rules = {
# Basic rules (implemented in apply):
# "D[f_ + g_, x_?NotListQ]": "D[f, x] + D[g, x]",
# "D[f_ * g_, x_?NotListQ]": "D[f, x] * g + f * D[g, x]",
# "D[f_ ^ r_, x_?NotListQ] /; FreeQ[r, x]": "r * f ^ (r-1) * D[f, x]",
# "D[E ^ f_, x_?NotListQ]": "E ^ f * D[f, x]",
# "D[f_ ^ g_, x_?NotListQ]": "D[E ^ (Log[f] * g), x]",
# Hacky: better implement them in apply
# "D[f_, x_?NotListQ] /; FreeQ[f, x]": "0",
# "D[f_[left___, x_, right___], x_?NotListQ] /; FreeQ[{left, right}, x]":
# "Derivative[Sequence @@ UnitVector["
# " Length[{left, x, right}], Length[{left, x}]]][f][left, x, right]",
# 'D[f_[args___], x_?NotListQ]':
# 'Plus @@ MapIndexed[(D[f[Sequence@@ReplacePart[{args}, #2->t]], t] '
# '/. t->#) * D[#, x]&, {args}]',
"D[{items___}, x_?NotListQ]": (
"Function[{System`Private`item}, D[System`Private`item, x]]" " /@ {items}"
),
# Handling iterated and vectorized derivative variables
"D[f_, {list_List}]": "D[f, #]& /@ list",
"D[f_, {list_List, n_Integer?Positive}]": (
"D[f, Sequence @@ ConstantArray[{list}, n]]"
),
"D[f_, x_, rest__]": "D[D[f, x], rest]",
"D[expr_, {x_, n_Integer?NonNegative}]": (
"Nest[Function[{t}, D[t, x]], expr, n]"
),
}
summary_text = "partial derivatives of scalar or vector functions"
sympy_name = "Derivative"
def eval(self, f, x, evaluation: Evaluation):
"D[f_, x_?NotListQ]"
# Handle partial derivative special cases:
# (dx / dx) == 1 and
# dx / d(expression not containing x) == 0
if f == x:
return Integer1
x_pattern = Pattern.create(x)
if f.is_free(x_pattern, evaluation):
return Integer0
# f is neither x nor does it not contain x
head = f.get_head()
if head is SymbolPlus:
terms = [
Expression(SymbolD, term, x)
for term in f.elements
if not term.is_free(x_pattern, evaluation)
]
if len(terms) == 0:
return Integer0
return Expression(SymbolPlus, *terms)
elif head is SymbolTimes:
terms = []
for i, factor in enumerate(f.elements):
if factor.is_free(x_pattern, evaluation):
continue
factors = [element for j, element in enumerate(f.elements) if j != i]
factors.append(Expression(SymbolD, factor, x))
terms.append(Expression(SymbolTimes, *factors))
if len(terms) != 0:
return Expression(SymbolPlus, *terms)
else:
return Integer0
elif head is SymbolPower and len(f.elements) == 2:
base, exp = f.elements
terms = []
if not base.is_free(x_pattern, evaluation):
terms.append(
Expression(
SymbolTimes,
exp,
Expression(
SymbolPower,
base,
Expression(SymbolPlus, exp, IntegerM1),
),
Expression(SymbolD, base, x),
)
)
if not exp.is_free(x_pattern, evaluation):
if isinstance(base, Atom) and base.get_name() == "System`E":
terms.append(
Expression(SymbolTimes, f, Expression(SymbolD, exp, x))
)
else:
terms.append(
Expression(
SymbolTimes,
f,
Expression(SymbolLog, base),
Expression(SymbolD, exp, x),
)
)
if len(terms) == 0:
return Integer0
elif len(terms) == 1:
return terms[0]
else:
return Expression(SymbolPlus, *terms)
elif len(f.elements) == 1:
if f.elements[0] == x:
return Expression(
Expression(Expression(SymbolDerivative, Integer1), f.head), x
)
else:
g = f.elements[0]
return Expression(
SymbolTimes,
Expression(SymbolD, Expression(f.head, g), g),
Expression(SymbolD, g, x),
)
else: # many elements
def summand(element, index):
result = Expression(
Expression(
Expression(
SymbolDerivative,
*(
[Integer0] * (index)
+ [Integer1]
+ [Integer0] * (len(f.elements) - index - 1)
),
),
f.head,
),
*f.elements,
)
if element.sameQ(x):
return result
else:
return Expression(
SymbolTimes, result, Expression(SymbolD, element, x)
)
result = [
summand(element, index)
for index, element in enumerate(f.elements)
if not element.is_free(x_pattern, evaluation)
]
if len(result) == 1:
return result[0]
elif len(result) == 0:
return Integer0
else:
return Expression(SymbolPlus, *result)
def eval_wrong(self, expr, x, other, evaluation: Evaluation):
"D[expr_, {x_, other___}]"
arg = ListExpression(x, *other.get_sequence())
evaluation.message("D", "dvar", arg)
return Expression(SymbolD, expr, arg)
class Derivative(PostfixOperator, SympyFunction):
"""
<url>:WMA link:
https://reference.wolfram.com/language/ref/Derivative.html</url>
<dl>
<dt>'Derivative[$n$][$f$]'
<dd>represents the $n$th derivative of the function $f$.
<dt>'Derivative[$n1$, $n2$, ...][$f$]'
<dd>represents a multivariate derivative.
</dl>
>> Derivative[1][Sin]
= Cos[#1]&
>> Derivative[3][Sin]
= -Cos[#1]&
>> Derivative[2][# ^ 3&]
= 6 #1&
'Derivative' can be entered using '\\'':
>> Sin'[x]
= Cos[x]
>> (# ^ 4&)''
= 12 #1 ^ 2&
>> f'[x] // InputForm
= Derivative[1][f][x]
>> Derivative[1][#2 Sin[#1]+Cos[#2]&]
= Cos[#1] #2&
>> Derivative[1,2][#2^3 Sin[#1]+Cos[#2]&]
= 6 Cos[#1] #2&
Deriving with respect to an unknown parameter yields 0:
>> Derivative[1,2,1][#2^3 Sin[#1]+Cos[#2]&]
= 0&
The 0th derivative of any expression is the expression itself:
>> Derivative[0,0,0][a+b+c]
= a + b + c
You can calculate the derivative of custom functions:
>> f[x_] := x ^ 2
>> f'[x]
= 2 x
Unknown derivatives:
>> Derivative[2, 1][h]
= Derivative[2, 1][h]
>> Derivative[2, 0, 1, 0][h[g]]
= Derivative[2, 0, 1, 0][h[g]]
## Parser Tests
#> Hold[f''] // FullForm
= Hold[Derivative[2][f]]
#> Hold[f ' '] // FullForm
= Hold[Derivative[2][f]]
#> Hold[f '' ''] // FullForm
= Hold[Derivative[4][f]]
#> Hold[Derivative[x][4] '] // FullForm
= Hold[Derivative[1][Derivative[x][4]]]
"""
attributes = A_N_HOLD_ALL
default_formats = False
operator = "'"
precedence = 670
rules = {
"MakeBoxes[Derivative[n__Integer][f_], "
" form:StandardForm|TraditionalForm]": (
r"SuperscriptBox[MakeBoxes[f, form], If[{n} === {2}, "
r' "\[Prime]\[Prime]", If[{n} === {1}, "\[Prime]", '
r' RowBox[{"(", Sequence @@ Riffle[{n}, ","], ")"}]]]]'
),
"MakeBoxes[Derivative[n:1|2][f_], form:OutputForm]": """RowBox[{MakeBoxes[f, form], If[n==1, "'", "''"]}]""",
# The following rules should be applied in the eval method, instead of relying on the pattern matching
# mechanism.
"Derivative[0...][f_]": "f",
"Derivative[n__Integer][Derivative[m__Integer][f_]] /; Length[{m}] "
"== Length[{n}]": "Derivative[Sequence @@ ({n} + {m})][f]",
# This would require at least some comments...
"""Derivative[n__Integer][f_Symbol] /; Module[{t=Sequence@@Slot/@Range[Length[{n}]], result, nothing, ft=f[t]},
If[Head[ft] === f
&& FreeQ[Join[UpValues[f], DownValues[f], SubValues[f]], Derivative|D]
&& Context[f] != "System`",
False,
(* else *)
ft = f[t];
Block[{f},
Unprotect[f];
(*Derivative[1][f] ^= nothing;*)
Derivative[n][f] ^= nothing;
Derivative[n][nothing] ^= nothing;
result = D[ft, Sequence@@Table[{Slot[i], {n}[[i]]}, {i, Length[{n}]}]];
];
FreeQ[result, nothing]
]
]""": """Module[{t=Sequence@@Slot/@Range[Length[{n}]], result, nothing, ft},
ft = f[t];
Block[{f},
Unprotect[f];
Derivative[n][f] ^= nothing;
Derivative[n][nothing] ^= nothing;
result = D[ft, Sequence@@Table[{Slot[i], {n}[[i]]}, {i, Length[{n}]}]];
];
Function @@ {result}
]""",
"Derivative[n__Integer][f_Function]": """Evaluate[D[
Quiet[f[Sequence @@ Table[Slot[i], {i, 1, Length[{n}]}]],
Function::slotn],
Sequence @@ Table[{Slot[i], {n}[[i]]}, {i, 1, Length[{n}]}]]]&""",
}
summary_text = "symbolic and numerical derivative functions"
def __init__(self, *args, **kwargs):
super(Derivative, self).__init__(*args, **kwargs)
def to_sympy(self, expr, **kwargs):
inner = expr
exprs = [inner]
try:
while True:
inner = inner.head
exprs.append(inner)
except AttributeError:
pass
if len(exprs) != 4 or not all(len(exp.elements) >= 1 for exp in exprs[:3]):
return
if len(exprs[0].elements) != len(exprs[2].elements):
return
sym_args = [element.to_sympy() for element in exprs[0].elements]
if None in sym_args:
return
func = exprs[1].elements[0]
sym_func = sympy.Function(str(sympy_symbol_prefix + func.__str__()))(*sym_args)
counts = [element.get_int_value() for element in exprs[2].elements]
if None in counts:
return
# sympy expects e.g. Derivative(f(x, y), x, 2, y, 5)
sym_d_args = []
for sym_arg, count in zip(sym_args, counts):
sym_d_args.append(sym_arg)
sym_d_args.append(count)
try:
return sympy.Derivative(sym_func, *sym_d_args)
except ValueError:
return
class DiscreteLimit(Builtin):
"""
<url>:WMA link:
https://reference.wolfram.com/language/ref/DiscreteLimit.html</url>
<dl>
<dt>'DiscreteLimit[$f$, $k$->Infinity]'
<dd>gives the limit of the sequence $f$ as $k$ tends to infinity.
</dl>
>> DiscreteLimit[n/(n + 1), n -> Infinity]
= 1
>> DiscreteLimit[f[n], n -> Infinity]
= f[Infinity]
"""
# TODO: Make this work
"""
>> DiscreteLimit[(n/(n + 2)) E^(-m/(m + 1)), {m -> Infinity, n -> Infinity}]
= 1 / E
"""
attributes = A_LISTABLE | A_PROTECTED
messages = {
"dltrials": "The value of Trials should be a positive integer",
}
options = {
"Trials": "5",
}
summary_text = "limits of sequences including recurrence and number theory"
def eval(self, f, n, n0, evaluation: Evaluation, options: dict = {}):
"DiscreteLimit[f_, n_->n0_, OptionsPattern[DiscreteLimit]]"
f = f.to_sympy(convert_all_global_functions=True)
n = n.to_sympy()
n0 = n0.to_sympy()
if n0 != sympy.oo:
return
if f is None or n is None:
return
trials = options["System`Trials"].get_int_value()
if trials is None or trials <= 0:
evaluation.message("DiscreteLimit", "dltrials")
trials = 5
try:
return from_sympy(sympy.limit_seq(f, n, trials))
except Exception:
pass
class _BaseFinder(Builtin):
"""
This class is the basis class for FindRoot, FindMinimum and FindMaximum.
"""
attributes = A_HOLD_ALL | A_PROTECTED
methods = {}
messages = {
"snum": "Value `1` is not a number.",
"nnum": "The function value is not a number at `1` = `2`.",
"dsing": "Encountered a singular derivative at the point `1` = `2`.",
"bdmthd": "Value option Method->`1` is not `2`",
"maxiter": (
"The maximum number of iterations was exceeded. "
"The result might be inaccurate."
),
"fmgz": (
"Encountered a gradient that is effectively zero. "
"The result returned may not be a `1`; "
"it may be a `2` or a saddle point."
),
}
options = {
"MaxIterations": "100",
"Method": "Automatic",
"AccuracyGoal": "Automatic",
"PrecisionGoal": "Automatic",
"StepMonitor": "None",
"EvaluationMonitor": "None",
"Jacobian": "Automatic",
}
def eval(self, f, x, x0, evaluation: Evaluation, options: dict):
"%(name)s[f_, {x_, x0_}, OptionsPattern[]]"
# This is needed to get the right messages
options["_isfindmaximum"] = self.__class__ is FindMaximum
# First, determine x0 and x
x0 = eval_N(x0, evaluation)
# deal with non 1D problems.
if isinstance(x0, Expression) and x0._head is SymbolList:
options["_x0"] = x0.elements
x0 = x0.elements[0]
if not isinstance(x0, Number):
evaluation.message(self.get_name(), "snum", x0)
return
x_name = x.get_name()
if not x_name:
evaluation.message(self.get_name(), "sym", x, 2)
return
# Now, get the explicit form of f, depending of x
# keeping x without evaluation (Like inside a "Block[{x},f])
f = dynamic_scoping(lambda ev: f.evaluate(ev), {x_name: None}, evaluation)
# If after evaluation, we get an "Equal" expression,
# convert it in a function by substracting both
# members. Again, ensure the scope in the evaluation
if f.get_head_name() == "System`Equal":
f = Expression(
SymbolPlus,
f.elements[0],
Expression(SymbolTimes, IntegerM1, f.elements[1]),
)
f = dynamic_scoping(lambda ev: f.evaluate(ev), {x_name: None}, evaluation)
# Determine the method
method = options["System`Method"]
if isinstance(method, Expression):
if method.get_head() is SymbolList:
method = method.elements[0]
if isinstance(method, Symbol):
method = method.get_name().split("`")[-1]
elif isinstance(method, String):
method = method.value
if not isinstance(method, str):
evaluation.message(
self.get_name(),
"bdmthd",
method,
[String(m) for m in self.methods.keys()],
)
return
# Determine the "jacobian"s
if (
method in ("Newton", "Automatic")
and options["System`Jacobian"] is SymbolAutomatic
):
def diff(evaluation):
return Expression(SymbolD, f, x).evaluate(evaluation)
d = dynamic_scoping(diff, {x_name: None}, evaluation)
options["System`Jacobian"] = d
method_caller = self.methods.get(method, None)
if method_caller is None:
evaluation.message(
self.get_name(),
"bdmthd",
method,
[String(m) for m in self.methods.keys()],
)
return
x0, success = method_caller(f, x0, x, options, evaluation)
if not success:
return
if isinstance(x0, tuple):
return ListExpression(
x0[1],
ListExpression(Expression(SymbolRule, x, x0[0])),
)
else:
return ListExpression(Expression(SymbolRule, x, x0))
def eval_with_x_tuple(self, f, xtuple, evaluation: Evaluation, options: dict):
"%(name)s[f_, xtuple_, OptionsPattern[]]"
f_val = f.evaluate(evaluation)
if f_val.has_form("Equal", 2):
f = Expression(SymbolPlus, f_val.elements[0], f_val.elements[1])
xtuple_value = xtuple.evaluate(evaluation)
if xtuple_value.has_form("List", None):
nelements = len(xtuple_value.elements)
if nelements == 2:
x, x0 = xtuple.evaluate(evaluation).elements
elif nelements == 3:
x, x0, x1 = xtuple.evaluate(evaluation).elements
options["$$Region"] = (x0, x1)
else:
return
return self.eval(f, x, x0, evaluation, options)
return
class FindMaximum(_BaseFinder):
r"""
<url>:WMA link:https://reference.wolfram.com/language/ref/FindMaximum.html</url>
<dl>
<dt>'FindMaximum[$f$, {$x$, $x0$}]'
<dd>searches for a numerical maximum of $f$, starting from '$x$=$x0$'.
</dl>
'FindMaximum' by default uses Newton\'s method, so the function of \
interest should have a first derivative.
>> FindMaximum[-(x-3)^2+2., {x, 1}]
: Encountered a gradient that is effectively zero. The result returned may not be a maximum; it may be a minimum or a saddle point.
= {2., {x -> 3.}}
>> FindMaximum[-10*^-30 *(x-3)^2+2., {x, 1}]
: Encountered a gradient that is effectively zero. The result returned may not be a maximum; it may be a minimum or a saddle point.
= {2., {x -> 3.}}
>> FindMaximum[Sin[x], {x, 1}]
= {1., {x -> 1.5708}}
>> phi[x_?NumberQ]:=NIntegrate[u, {u, 0., x}, Method->"Internal"];
>> Quiet[FindMaximum[-phi[x] + x, {x, 1.2}, Method->"Newton"]]
= {0.5, {x -> 1.00001}}
>> Clear[phi];
For a not so well behaving function, the result can be less accurate:
>> FindMaximum[-Exp[-1/x^2]+1., {x,1.2}, MaxIterations->10]
: The maximum number of iterations was exceeded. The result might be inaccurate.
= FindMaximum[-Exp[-1 / x ^ 2] + 1., {x, 1.2}, MaxIterations -> 10]
"""
methods = {}
messages = _BaseFinder.messages.copy()
summary_text = "local maximum optimization"
try:
from mathics.algorithm.optimizers import native_local_optimizer_methods
methods.update(native_local_optimizer_methods)
except Exception:
pass
try:
from mathics.builtin.scipy_utils.optimizers import scipy_optimizer_methods
methods.update(scipy_optimizer_methods)
except Exception:
pass
class FindMinimum(_BaseFinder):
r"""
<url>:WMA link:
https://reference.wolfram.com/language/ref/FindMinimum.html</url>
<dl>
<dt>'FindMinimum[$f$, {$x$, $x0$}]'
<dd>searches for a numerical minimum of $f$, starting from '$x$=$x0$'.
</dl>
'FindMinimum' by default uses Newton\'s method, so the function of \
interest should have a first derivative.
>> FindMinimum[(x-3)^2+2., {x, 1}]
: Encountered a gradient that is effectively zero. The result returned may not be a minimum; it may be a maximum or a saddle point.
= {2., {x -> 3.}}
>> FindMinimum[10*^-30 *(x-3)^2+2., {x, 1}]
: Encountered a gradient that is effectively zero. The result returned may not be a minimum; it may be a maximum or a saddle point.
= {2., {x -> 3.}}
>> FindMinimum[Sin[x], {x, 1}]
= {-1., {x -> -1.5708}}
>> phi[x_?NumberQ]:=NIntegrate[u,{u,0,x}, Method->"Internal"];
>> Quiet[FindMinimum[phi[x]-x,{x, 1.2}, Method->"Newton"]]
= {-0.5, {x -> 1.00001}}
>> Clear[phi];
For a not so well behaving function, the result can be less accurate:
>> FindMinimum[Exp[-1/x^2]+1., {x,1.2}, MaxIterations->10]
: The maximum number of iterations was exceeded. The result might be inaccurate.
= FindMinimum[Exp[-1 / x ^ 2] + 1., {x, 1.2}, MaxIterations -> 10]
"""
methods = {}
messages = _BaseFinder.messages.copy()
summary_text = "local minimum optimization"
try:
from mathics.algorithm.optimizers import (
native_local_optimizer_methods,
native_optimizer_messages,
)
methods.update(native_local_optimizer_methods)
messages.update(native_optimizer_messages)
except Exception:
pass
try:
from mathics.builtin.scipy_utils.optimizers import scipy_optimizer_methods
methods.update(scipy_optimizer_methods)
except Exception:
pass
class FindRoot(_BaseFinder):
r"""
<url>:WMA link:https://reference.wolfram.com/language/ref/FindRoot.html</url>
<dl>
<dt>'FindRoot[$f$, {$x$, $x0$}]'
<dd>searches for a numerical root of $f$, starting from '$x$=$x0$'.
<dt>'FindRoot[$lhs$ == $rhs$, {$x$, $x0$}]'
<dd>tries to solve the equation '$lhs$ == $rhs$'.
</dl>
'FindRoot' by default uses Newton\'s method, so the function of interest \
should have a first derivative.
>> FindRoot[Cos[x], {x, 1}]
= {x -> 1.5708}
>> FindRoot[Sin[x] + Exp[x],{x, 0}]
= {x -> -0.588533}
>> FindRoot[Sin[x] + Exp[x] == Pi,{x, 0}]
= {x -> 0.866815}
'FindRoot' has attribute 'HoldAll' and effectively uses 'Block' to localize $x$.
However, in the result $x$ will eventually still be replaced by its value.
>> x = "I am the result!";
>> FindRoot[Tan[x] + Sin[x] == Pi, {x, 1}]
= {I am the result! -> 1.14911}
>> Clear[x]
'FindRoot' stops after 100 iterations:
>> FindRoot[x^2 + x + 1, {x, 1}]
: The maximum number of iterations was exceeded. The result might be inaccurate.
= {x -> -1.}
Find complex roots:
>> FindRoot[x ^ 2 + x + 1, {x, -I}]
= {x -> -0.5 - 0.866025 I}
The function has to return numerical values:
>> FindRoot[f[x] == 0, {x, 0}]
: The function value is not a number at x = 0..
= FindRoot[f[x] - 0, {x, 0}]
The derivative must not be 0:
>> FindRoot[Sin[x] == x, {x, 0}]
: Encountered a singular derivative at the point x = 0..
= FindRoot[Sin[x] - x, {x, 0}]
#> FindRoot[2.5==x,{x,0}]
= {x -> 2.5}
>> FindRoot[x^2 - 2, {x, 1,3}, Method->"Secant"]
= {x -> 1.41421}
"""
rules = {
"FindRoot[lhs_ == rhs_, {x_, xs_}, opt:OptionsPattern[]]": "FindRoot[lhs-rhs, {x, xs}, opt]",
"FindRoot[lhs_ == rhs_, x__, opt:OptionsPattern[]]": "FindRoot[lhs-rhs, x, opt]",
}
messages = _BaseFinder.messages.copy()
methods = {}
summary_text = (
"Looks for a root of an equation or a zero of a numerical expression."
)
try:
from mathics.algorithm.optimizers import (
native_findroot_messages,
native_findroot_methods,
)
methods.update(native_findroot_methods)
messages.update(native_findroot_messages)
except Exception:
pass
try:
from mathics.builtin.scipy_utils.optimizers import (
scipy_findroot_methods,
update_findroot_messages,
)
methods.update(scipy_findroot_methods)
messages = _BaseFinder.messages.copy()
update_findroot_messages(messages)
except Exception:
pass
# Move to mathics.builtin.domains...
class Integers(Builtin):
"""
<url>:WMA link:https://reference.wolfram.com/language/ref/Integers.html</url>
<dl>
<dt>'Integers'
<dd>the domain of integer numbers, as in $x$ in Integers.
</dl>
Limit a solution to integer numbers:
>> Solve[-4 - 4 x + x^4 + x^5 == 0, x, Integers]
= {{x -> -1}}
>> Solve[x^4 == 4, x, Integers]
= {}
"""
summary_text = "the domain integers numbers"
class Integrate(SympyFunction):
r"""
<url>:WMA link:
https://reference.wolfram.com/language/ref/Integrate.html</url>
<dl>
<dt>'Integrate[$f$, $x$]'
<dd>integrates $f$ with respect to $x$. The result does not contain the \
additive integration constant.
<dt>'Integrate[$f$, {$x$, $a$, $b$}]'
<dd>computes the definite integral of $f$ with respect to $x$ from $a$ to $b$.
</dl>
Integrate a polynomial:
>> Integrate[6 x ^ 2 + 3 x ^ 2 - 4 x + 10, x]
= x (10 - 2 x + 3 x ^ 2)
Integrate trigonometric functions:
>> Integrate[Sin[x] ^ 5, x]
= Cos[x] (-1 - Cos[x] ^ 4 / 5 + 2 Cos[x] ^ 2 / 3)
Definite integrals:
>> Integrate[x ^ 2 + x, {x, 1, 3}]
= 38 / 3
>> Integrate[Sin[x], {x, 0, Pi/2}]
= 1
Some other integrals:
>> Integrate[1 / (1 - 4 x + x^2), x]
= Sqrt[3] (Log[-2 - Sqrt[3] + x] - Log[-2 + Sqrt[3] + x]) / 6
>> Integrate[4 Sin[x] Cos[x], x]
= 2 Sin[x] ^ 2
> Integrate[-Infinity, {x, 0, Infinity}]
= -Infinity
> Integrate[-Infinity, {x, Infinity, 0}]
= Infinity
Integration in TeX:
>> Integrate[f[x], {x, a, b}] // TeXForm
= \int_a^b f\left[x\right] \, dx
#> DownValues[Integrate]
= {}
#> Definition[Integrate]
= Attributes[Integrate] = {Protected, ReadProtected}
.
. Options[Integrate] = {Assumptions -> $Assumptions, GenerateConditions -> Automatic, PrincipalValue -> False}
#> Integrate[Hold[x + x], {x, a, b}]
= Integrate[Hold[x + x], {x, a, b}]
#> Integrate[sin[x], x]
= Integrate[sin[x], x]
#> Integrate[x ^ 3.5 + x, x]
= x ^ 2 / 2 + 0.222222 x ^ 4.5
Sometimes there is a loss of precision during integration.
You can check the precision of your result with the following sequence
of commands.
>> Integrate[Abs[Sin[phi]], {phi, 0, 2Pi}] // N
= 4.
>> % // Precision
= MachinePrecision
#> Integrate[1/(x^5+1), x]
= RootSum[1 + 5 #1 + 25 #1 ^ 2 + 125 #1 ^ 3 + 625 #1 ^ 4&, Log[x + 5 #1] #1&] + Log[1 + x] / 5
#> Integrate[ArcTan(x), x]
= x ^ 2 ArcTan / 2
#> Integrate[E[x], x]