-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculus.js
More file actions
2196 lines (2122 loc) · 86.4 KB
/
Calculus.js
File metadata and controls
2196 lines (2122 loc) · 86.4 KB
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
if (typeof module !== "undefined" && typeof nerdamer === "undefined") {
nerdamer = require("./nerdamer.core.js");
require("./Algebra.js");
}
(function () {
"use strict";
var core = nerdamer.getCore(),
_ = core.PARSER,
Frac = core.Frac,
isSymbol = core.Utils.isSymbol,
FN = core.groups.FN,
Symbol = core.Symbol,
text = core.Utils.text,
inBrackets = core.Utils.inBrackets,
isInt = core.Utils.isInt,
format = core.Utils.format,
even = core.Utils.even,
N = core.groups.N,
S = core.groups.S,
FN = core.groups.FN,
PL = core.groups.PL,
CP = core.groups.CP,
CB = core.groups.CB,
EX = core.groups.EX,
P = core.groups.P,
LOG = "log",
EXP = "exp",
ABS = "abs",
SQRT = "sqrt",
SIN = "sin",
COS = "cos",
TAN = "tan",
SEC = "sec",
CSC = "csc",
COT = "cot",
ASIN = "asin",
ACOS = "acos",
ATAN = "atan",
ASEC = "asec",
ACSC = "acsc",
ACOT = "acot",
SINH = "sinh",
COSH = "cosh",
TANH = "tanh";
//custom errors
function NoIntegralFound(msg) {
this.message = msg || "";
}
NoIntegralFound.prototype = new Error();
//Preparations
Symbol.prototype.hasIntegral = function () {
return this.containsFunction("integrate");
};
//transforms a function
Symbol.prototype.fnTransform = function () {
var retval,
a = this.args[0];
if (this.isLinear()) {
switch (this.fname) {
case SINH:
retval = _.parse(format("(e^({0})-e^(-({0})))/2", a));
break;
case COSH:
retval = _.parse(format("(e^({0})+e^(-({0})))/2", a));
break;
case TANH:
retval = _.parse(
format("(e^({0})-e^(-({0})))/(e^({0})+e^(-({0})))", a)
);
break;
case TAN:
retval = _.parse(format("sin({0})/cos({0})", a));
break;
case CSC:
retval = _.parse(format("1/sin({0})", a));
break;
case SEC:
retval = _.parse(format("1/cos({0})", a));
break;
default:
retval = this;
}
} else if (this.power.equals(2)) {
switch (this.fname) {
case SIN:
retval = _.parse(format("1/2-cos(2*({0}))/2", a));
break;
case COS:
retval = _.parse(format("1/2+cos(2*({0}))/2", a));
break;
case TAN:
//retval = _.parse(format('(1-cos(2*({0})))/(1+cos(2*({0})))', a));
retval = _.parse(format("sin({0})^2/cos({0})^2", a));
break;
case COSH:
retval = _.parse(format("1/2+cosh(2*({0}))/2", a));
break;
case SINH:
retval = _.parse(format("-1/2+cosh(2*({0}))/2", a));
break;
case TANH:
retval = _.parse(format("(1+cosh(2*({0})))/(-1+cosh(2*({0})))", a));
break;
case SEC:
retval = _.parse(format("(1-cos(2*({0})))/(1+cos(2*({0})))+1", a));
break;
default:
retval = this;
}
} else if (this.fname === SEC) {
retval = _.parse(format("1/cos({0})^({1})", this.args[0], this.power));
} else if (this.fname === CSC) {
retval = _.parse(format("1/sin({0})^({1})", this.args[0], this.power));
} else if (this.fname === TAN) {
if (this.power.lessThan(0)) {
retval = _.parse(
format(
"cos({0})^({1})/sin({0})^({1})",
this.args[0],
this.power.clone().negate()
)
);
} else {
retval = _.parse(
format("sin({0})^({1})/cos({0})^({1})", this.args[0], this.power)
);
}
} else if (this.fname === SIN && this.power.lessThan(0)) {
retval = _.parse(
format("csc({0})^({1})", this.args[0], this.power.clone().negate())
);
} else if (this.fname === COS && this.power.lessThan(0)) {
retval = _.parse(
format("sec({0})^({1})", this.args[0], this.power.clone().negate())
);
} else if (this.fname === SIN && this.power.equals(3)) {
retval = _.parse(format("(3*sin({0})-sin(3*({0})))/4", this.args[0]));
} else if (this.fname === COS && this.power.equals(3)) {
retval = _.parse(format("(cos(3*({0}))+3*cos({0}))/4", this.args[0]));
} else retval = this;
return retval;
};
//removes parentheses
Symbol.unwrapPARENS = function (symbol) {
if (symbol.group === FN && !symbol.fname) {
var r = symbol.args[0];
r.power = r.power.multiply(symbol.power);
r.multiplier = r.multiplier.multiply(symbol.multiplier);
return r;
}
return symbol;
};
core.Expression.prototype.hasIntegral = function () {
return this.symbol.hasIntegral();
};
//A function to check if a function name is an inverse trig function
core.Utils.in_inverse_trig = function (x) {
var inv_trig_fns = [ASIN, ACOS, ATAN, ACSC, ASEC, ACOT];
return inv_trig_fns.indexOf(x) !== -1;
};
//A function to check if a function name is a trig function
core.Utils.in_trig = function (x) {
var trig_fns = [COS, SIN, TAN, SEC, CSC, COT];
return trig_fns.indexOf(x) !== -1;
};
core.Utils.in_htrig = function (x) {
var trig_fns = ["sinh", "cosh", "tanh"];
return trig_fns.indexOf(x) !== -1;
};
var all_functions = (core.Utils.all_functions = function (arr) {
for (var i = 0, l = arr.length; i < l; i++)
if (arr[i].group !== FN) return false;
return true;
}),
cosAsinBtransform = (core.Utils.cosAsinBtranform = function (
symbol1,
symbol2
) {
var a, b;
a = symbol1.args[0].clone();
b = symbol2.args[0].clone();
return _.parse(format("(sin(({0})+({1}))-sin(({0})-({1})))/2", a, b));
}),
cosAsinAtransform = (core.Utils.cosAsinAtranform = function (
symbol1,
symbol2
) {
var a;
a = symbol1.args[0].clone();
return _.parse(format("(sin(2*({0})))/2", a));
}),
sinAsinBtransform = (core.Utils.cosAsinBtranform = function (
symbol1,
symbol2
) {
var a, b;
a = symbol1.args[0].clone();
b = symbol2.args[0].clone();
return _.parse(format("(cos(({0})+({1}))-cos(({0})-({1})))/2", a, b));
}),
trigTransform = (core.Utils.trigTransform = function (arr) {
var map = {},
symbol,
t,
retval = new Symbol(1);
for (var i = 0, l = arr.length; i < l; i++) {
symbol = arr[i];
if (symbol.group === FN) {
var fname = symbol.fname;
if (fname === COS && map[SIN]) {
if (map[SIN].args[0].toString() !== symbol.args[0].toString()) {
t = cosAsinBtransform(symbol, map[SIN]);
delete map[SIN];
} else {
t = cosAsinAtransform(symbol, map[SIN]);
delete map[SIN];
}
retval = _.multiply(retval, t);
} else if (fname === SIN && map[COS]) {
if (map[COS].args[0].toString() !== symbol.args[0].toString()) {
t = cosAsinBtransform(symbol, map[COS]);
delete map[COS];
} else {
t = cosAsinAtransform(symbol, map[COS]);
delete map[COS];
}
retval = _.multiply(retval, t);
} else if (fname === SIN && map[SIN]) {
if (map[SIN].args[0].toString() !== symbol.args[0].toString()) {
t = sinAsinBtransform(symbol, map[SIN]);
delete map[SIN];
} else {
//This should actually be redundant code but let's put just in case
t = _.multiply(symbol, map[SIN]);
delete map[SIN];
}
retval = t;
} else map[fname] = symbol;
} else retval = _.multiply(retval, symbol);
}
//put back the remaining functions
for (var x in map) retval = _.multiply(retval, map[x]);
return retval;
});
core.Settings.integration_depth = 10;
var __ = (core.Calculus = {
version: "1.4.2",
sum: function (fn, index, start, end) {
if (!(index.group === core.groups.S))
throw new Error("Index must be symbol. " + text(index) + " provided");
index = index.value;
var retval;
if (
core.Utils.isNumericSymbol(start) &&
core.Utils.isNumericSymbol(end)
) {
start = start.multiplier;
end = end.multiplier;
var variables = core.Utils.variables(fn);
if (variables.length === 1 && index === variables[0]) {
var f = core.Utils.build(fn);
retval = 0;
for (var i = start; i <= end; i++) {
retval += f.call(undefined, i);
}
retval = new Symbol(retval);
} else {
var f = fn.text(),
subs = { "~": true }, //lock subs. Is this even being used?
retval = new core.Symbol(0);
for (var i = start; i <= end; i++) {
subs[index] = new Symbol(i);
retval = _.add(retval, _.parse(f, subs));
}
}
} else {
retval = _.symfunction("sum", arguments);
}
return retval;
},
product: function (fn, index, start, end) {
if (!(index.group === core.groups.S))
throw new Error("Index must be symbol. " + text(index) + " provided");
index = index.value;
var retval;
if (
core.Utils.isNumericSymbol(start) &&
core.Utils.isNumericSymbol(end)
) {
start = start.multiplier;
end = end.multiplier;
var f = fn.text(),
subs = {},
retval = new core.Symbol(1);
for (var i = start; i <= end; i++) {
subs[index] = new Symbol(i);
retval = _.multiply(retval, _.parse(f, subs));
}
} else {
retval = _.symfunction("product", arguments);
}
return retval;
},
diff: function (symbol, wrt, nth) {
if (core.Utils.isVector(symbol)) {
var vector = new core.Vector([]);
symbol.each(function (x) {
vector.elements.push(__.diff(x, wrt));
});
return vector;
}
var d = isSymbol(wrt) ? wrt.text() : wrt;
//the nth derivative
nth = isSymbol(nth) ? nth.multiplier : nth || 1;
if (d === undefined) d = core.Utils.variables(symbol)[0];
//unwrap sqrt
if (symbol.group === FN && symbol.fname === SQRT) {
var s = symbol.args[0],
sp = symbol.power.clone();
//these groups go to zero anyway so why waste time?
if (s.group !== N || s.group !== P) {
s.power = isSymbol(s.power)
? _.multiply(s.power, _.multiply(new Symbol(1 / 2)), sp)
: s.power.multiply(new Frac(0.5)).multiply(sp);
s.multiplier = s.multiplier.multiply(symbol.multiplier);
}
symbol = s;
}
if (symbol.group === FN && !isSymbol(symbol.power)) {
var a = derive(symbol);
var b = __.diff(symbol.args[0].clone(), d);
symbol = _.multiply(a, b); //chain rule
} else {
symbol = derive(symbol);
}
if (nth > 1) {
nth--;
symbol = __.diff(symbol, wrt, nth);
}
return symbol;
// Equivalent to "derivative of the outside".
function polydiff(symbol) {
if (symbol.value === d || symbol.contains(d, true)) {
symbol.multiplier = symbol.multiplier.multiply(symbol.power);
symbol.power = symbol.power.subtract(new Frac(1));
if (symbol.power.equals(0)) {
symbol = Symbol(symbol.multiplier);
}
}
return symbol;
}
function derive(symbol) {
var g = symbol.group,
a,
b,
cp;
if (g === N || (g === S && symbol.value !== d) || g === P) {
symbol = Symbol(0);
} else if (g === S) {
symbol = polydiff(symbol);
} else if (g === CB) {
var m = symbol.multiplier.clone();
symbol.toUnitMultiplier();
var retval = _.multiply(
product_rule(symbol),
polydiff(symbol.clone())
);
retval.multiplier = retval.multiplier.multiply(m);
return retval;
} else if (g === FN && symbol.power.equals(1)) {
// Table of known derivatives
switch (symbol.fname) {
case LOG:
cp = symbol.clone();
symbol = symbol.args[0].clone(); //get the arguments
symbol.power = symbol.power.negate();
symbol.multiplier = cp.multiplier.divide(symbol.multiplier);
break;
case COS:
//cos -> -sin
symbol.fname = SIN;
symbol.multiplier.negate();
break;
case SIN:
//sin -> cos
symbol.fname = COS;
break;
case TAN:
//tan -> sec^2
symbol.fname = SEC;
symbol.power = new Frac(2);
break;
case SEC:
// Use a clone if this gives errors
symbol = qdiff(symbol, TAN);
break;
case CSC:
symbol = qdiff(symbol, "-cot");
break;
case COT:
symbol.fname = CSC;
symbol.multiplier.negate();
symbol.power = new Frac(2);
break;
case ASIN:
symbol = _.parse(
"(sqrt(1-(" + text(symbol.args[0]) + ")^2))^(-1)"
);
break;
case ACOS:
symbol = _.parse(
"-(sqrt(1-(" + text(symbol.args[0]) + ")^2))^(-1)"
);
break;
case ATAN:
symbol = _.parse("(1+(" + text(symbol.args[0]) + ")^2)^(-1)");
break;
case ABS:
m = symbol.multiplier.clone();
symbol.toUnitMultiplier();
//depending on the complexity of the symbol it's easier to just parse it into a new symbol
//this should really be readdressed soon
b = symbol.args[0].clone();
b.toUnitMultiplier();
symbol = _.parse(
inBrackets(text(symbol.args[0])) + "/abs" + inBrackets(text(b))
);
symbol.multiplier = m;
break;
case "parens":
//see product rule: f'.g goes to zero since f' will return zero. This way we only get back
//1*g'
symbol = Symbol(1);
break;
case "cosh":
//cosh -> -sinh
symbol.fname = "sinh";
break;
case "sinh":
//sinh -> cosh
symbol.fname = "cosh";
break;
case "tanh":
//tanh -> sech^2
symbol.fname = "sech";
symbol.power = new Frac(2);
break;
case "sech":
// Use a clone if this gives errors
symbol = qdiff(symbol, "-tanh");
break;
case "asinh":
symbol = _.parse(
"(sqrt(1+(" + text(symbol.args[0]) + ")^2))^(-1)"
);
break;
case "acosh":
symbol = _.parse(
"(sqrt(-1+(" + text(symbol.args[0]) + ")^2))^(-1)"
);
break;
case "atanh":
symbol = _.parse("(1-(" + text(symbol.args[0]) + ")^2)^(-1)");
break;
case "Si":
var arg = symbol.args[0];
symbol = _.parse("sin(" + arg + ")/(" + arg + ")");
break;
case "Shi":
var arg = symbol.args[0];
symbol = _.parse("sinh(" + arg + ")/(" + arg + ")");
break;
case "Ci":
var arg = symbol.args[0];
symbol = _.parse("cos(" + arg + ")/(" + arg + ")");
break;
case "Chi":
var arg = symbol.args[0];
symbol = _.parse("cosh(" + arg + ")/(" + arg + ")");
break;
case "Ei":
var arg = symbol.args[0];
symbol = _.parse("e^(" + arg + ")/(" + arg + ")");
break;
}
} else if (g === EX || (g === FN && isSymbol(symbol.power))) {
var value;
if (g === EX) {
value = symbol.value;
} else if (g === FN && symbol.contains(d)) {
value = symbol.fname + inBrackets(text(symbol.args[0]));
} else {
value = symbol.value + inBrackets(text(symbol.args[0]));
}
a = _.multiply(
_.parse(LOG + inBrackets(value)),
symbol.power.clone()
);
b = __.diff(
_.multiply(_.parse(LOG + inBrackets(value)), symbol.power.clone()),
d
);
symbol = _.multiply(symbol, b);
} else if (g === FN && !symbol.power.equals(1)) {
b = symbol.clone();
b.toLinear();
b.toUnitMultiplier();
symbol = _.multiply(polydiff(symbol.clone(), d), derive(b));
} else if (g === CP || g === PL) {
var result = new Symbol(0);
for (var x in symbol.symbols) {
result = _.add(result, __.diff(symbol.symbols[x].clone(), d));
}
symbol = _.multiply(polydiff(symbol.clone()), result);
}
symbol.updateHash();
return symbol;
}
function qdiff(symbol, val, altVal) {
return _.multiply(
symbol,
_.parse(val + inBrackets(altVal || text(symbol.args[0])))
);
}
function product_rule(symbol) {
//grab all the symbols within the CB symbol
var symbols = symbol.collectSymbols(),
result = new Symbol(0),
l = symbols.length;
//loop over all the symbols
for (var i = 0; i < l; i++) {
var df = __.diff(symbols[i].clone(), d);
for (var j = 0; j < l; j++) {
//skip the symbol of which we just pulled the derivative
if (i !== j) {
//multiply out the remaining symbols
df = _.multiply(df, symbols[j].clone());
}
}
//add the derivative to the result
result = _.add(result, df);
}
return result; //done
}
},
integration: {
u_substitution: function (symbols, dx) {
function try_combo(a, b, f) {
var q = f ? f(a, b) : _.divide(a.clone(), __.diff(b, dx));
if (!q.contains(dx, true)) return q;
return null;
}
function do_fn_sub(fname, arg) {
var subbed = __.integrate(
_.symfunction(fname, [new Symbol(u)]),
u,
0
);
subbed = subbed.sub(new Symbol(u), arg);
subbed.updateHash();
return subbed;
}
var a = symbols[0].clone(),
b = symbols[1].clone(),
g1 = a.group,
g2 = b.group,
//may cause problems if person is using this already. Will need
//to find algorithm for detecting conflict
u = "__u__",
Q;
if (g1 === FN && g2 !== FN) {
//e.g. 2*x*cos(x^2)
var arg = a.args[0];
Q = try_combo(b, arg.clone());
if (Q) return _.multiply(Q, do_fn_sub(a.fname, arg));
Q = try_combo(b, a);
if (Q) {
return __.integration.poly_integrate(a);
}
} else if (g2 === FN && g1 !== FN) {
//e.g. 2*(x+1)*cos((x+1)^2
var arg = b.args[0];
Q = try_combo(a, arg.clone());
if (Q) return _.multiply(Q, do_fn_sub(b.fname, arg));
} else if (g1 === FN && g1 === FN) {
Q = try_combo(a.clone(), b.clone());
if (Q) return _.multiply(__.integration.poly_integrate(b), Q);
Q = try_combo(b.clone(), a.clone());
if (Q) return _.multiply(__.integration.poly_integrate(b), Q);
} else if (g1 === EX && g2 !== EX) {
var p = a.power;
Q = try_combo(b, p.clone());
if (!Q) {
//one more try
var dc = __.integration.decompose_arg(p.clone(), dx);
//consider the possibility of a^x^(n-1)*x^n dx
var xp = __.diff(dc[2].clone(), dx);
var dc2 = __.integration.decompose_arg(xp.clone(), dx);
//if their powers equal, so if dx*p == b
if (_.multiply(dc[1], dc2[1]).power.equals(b.power)) {
var m = _.divide(dc[0].clone(), dc2[0].clone());
var new_val = _.multiply(
m.clone(),
_.pow(new Symbol(a.value), _.multiply(dc[0], new Symbol(u)))
);
new_val = _.multiply(new_val, new Symbol(u));
return __.integration
.by_parts(new_val, u, 0, {})
.sub(u, dc[1].clone());
}
}
var integrated = __.integrate(a.sub(p.clone(), new Symbol(u)), u, 0),
retval = _.multiply(integrated.sub(new Symbol(u), p), Q);
return retval;
} else if (g2 === EX && g1 !== EX) {
var p = b.power;
Q = try_combo(a, p.clone());
var integrated = __.integrate(b.sub(p, new Symbol(u)), u, 0);
return _.multiply(integrated.sub(new Symbol(u), p), Q);
} else if (a.isComposite() || b.isComposite()) {
var f = function (a, b) {
var A = core.Algebra.Factor.factor(a),
B = core.Algebra.Factor.factor(__.diff(b, dx));
var q = _.divide(A, B);
return q;
};
var f1 = a.isComposite() ? a.clone().toLinear() : a.clone(),
f2 = b.isComposite() ? b.clone().toLinear() : b.clone();
Q = try_combo(f1.clone(), f2.clone(), f);
if (Q) return _.multiply(__.integration.poly_integrate(b), Q);
Q = try_combo(f2.clone(), f1.clone(), f);
if (Q) return _.multiply(__.integration.poly_integrate(a), Q);
}
},
//simple integration of a single polynomial x^(n+1)/(n+1)
poly_integrate: function (x) {
var p = x.power.toString(),
m = x.multiplier.toDecimal(),
s = x.toUnitMultiplier().toLinear();
if (Number(p) === -1) {
return _.multiply(new Symbol(m), _.symfunction(LOG, [s]));
}
return _.parse(format("({0})*({1})^(({2})+1)/(({2})+1)", m, s, p));
},
//If we're just spinning wheels we want to stop. This is why we
//wrap integration in a try catch block and call this to stop.
stop: function (msg) {
msg = msg || "Stopping!";
throw new NoIntegralFound(msg);
},
partial_fraction: function (input, dx, depth, opt) {
var num, den;
var m = new Symbol(input.multiplier);
//make prepartions
//check if it's a symbol. If so get num and denom
if (isSymbol(input)) {
den = input.getDenom().invert();
num = input.getNum();
} else {
//we assume it's an array
num = input[0];
den = input[1];
}
//although technically not partial fractions we can save ourselves a lot of headache with a simple u sub
if (num.isConstant()) {
var fn = den.clone().toLinear(),
a = fn.stripVar(dx),
bx = _.subtract(fn.clone(), a);
if (bx.group === S && bx.isLinear()) {
//we make the u substitution
return __.integration.poly_integrate(input);
}
if (den.power.greaterThan(1)) den = _.expand(den);
}
//make sure that den > num
var q = core.Algebra.div(num, den.clone()),
M = new core.Matrix(), //prepare the two matrices
c = new core.Matrix(),
num_array = q[1].toArray(dx), //point to the remainder not the numerator
num = q[1]; //point to the remainder not the whole
//get the factors of the denominator
var factors = Symbol.unwrapPARENS(core.Algebra.Factor.factor(den));
var factor_array = [];
//we first have to unwrap the factor and get them in ordered form. We use an array for this
//the first part of q can just be integrated using standard integration so we do so
var result = q[0].equals(0) ? q[0] : __.integrate(q[0], dx, depth || 0);
if (factors.group !== CP) {
factors.each(function (factor) {
//unwrap parentheses
factor = Symbol.unwrapPARENS(factor);
//TODO: red flag. Possible bug. The factors should already be inverted. Why are we inverting them here?
if (factor.power.lessThan(0)) factor.invert();
if (factor.isConstant()) m = _.multiply(m, factor);
//add it to the constants
else factor_array.push(factor);
});
} else {
if (q[1].isComposite()) {
//apply the sum rule
q[1].each(function (x) {
var s = _.divide(x.clone(), factors.clone()); //put it back in the form num/den
result = _.add(result, __.integrate(s, dx, depth || 0));
});
} else {
//I have no idea why integration by parts doesn't work for p === 2
var fn = factors.clone().toLinear(),
decomp = __.integration.decompose_arg(fn, dx),
x = decomp[1],
a = decomp[0],
b = decomp[3];
if (!x.isLinear())
//we stop because u du takes care of quadratics
__.integration.stop();
if (factors.power.greaterThan(0)) {
if (q[1].isConstant()) {
result = __.integration.poly_integrate(_.divide(q[1], factors));
} else {
//since we know x is linear we can just let u = x+a and u-a = x = r
//TODO: On a serious note what is u du doing in partial fractions. This has got to be redone
//rewrite the expression to become (1/a)*[ (ax+b)/(ax+b) - b/(ax+b)] which we can do
//since x is linear from above
result = _.add(
__.integrate(
_.divide(fn.clone(), factors.clone()),
dx,
depth || 0
),
__.integrate(
_.divide(b.negate(), factors.clone()),
dx,
depth || 0
)
);
}
result = _.divide(result, a);
} else {
result = __.integration.by_parts(
_.divide(q[1], factors.clone()),
dx,
core.Settings.integration_depth,
opt
);
}
}
return result;
}
var l = factor_array.length;
//if there's only one factor then we can exit since there's nothing else to compute
//other than the current integral of the whole and remainder
if (l === 1) {
//put it back in the proper form. Remember that this is the remainder so it still has a
//denominator
var s = _.divide(q[1], factor_array[0]);
var intg = __.integrate(s, dx, depth || 0); //compute the integral of the remainder
intg = _.divide(intg, m); //put back the multiplier
result = _.add(result, intg);
return result;
}
//the next step is to expand the factors excluding the current factor
//e.g. if the factors were (x+7)*(x+1)*(x+5) we want them as:
//x^2+6*x+5 because of: (x+1)*(x+5)
//x^2+12*x+35 because of: (x+7)*(x+5)
//x^2+8*x+7 because of: (x+7)*(x+1)
for (var i = 0; i < l; i++) {
var t = new Symbol(1);
for (var j = 0; j < l; j++) {
if (i !== j) t = _.multiply(t, factor_array[j].clone());
}
t = _.expand(t).toArray(dx); //this is one of the rows
var e = num_array[i];
c.elements[i] = e ? [e] : [Symbol(0)]; //fill the holes in the coeffs
M.elements[i] = t; //add the row to the matrix
}
//solve for A, B, C, etc. We transpose to have the powers in the columns
var L = M.transpose().invert().multiply(c);
//we can now integrate each one of them but remember we divided earlier so integrate the whole if it's not zero
for (var i = 0; i < l; i++) {
var integral = __.integrate(
_.divide(q[1].clone(), factor_array[i]),
dx,
depth || 0
),
cf = _.expand(L.elements[i][0]);
var mm = _.divide(cf, m.clone());
result = _.add(result, _.multiply(integral, mm));
}
return result;
},
get_udv: function (symbol) {
var parts = [
[
/*L*/
],
[
/*I*/
],
[
/*A*/
],
[
/*T*/
],
[
/*E*/
]
];
//first we sort them
var setSymbol = function (x) {
var g = x.group;
if (g === FN) {
var fname = x.fname;
if (core.Utils.in_trig(fname) || core.Utils.in_htrig(fname))
parts[3].push(x);
else if (core.Utils.in_inverse_trig(fname)) parts[1].push(x);
else if (fname === LOG) parts[0].push(x);
else {
__.integration.stop();
}
} else if (
g === S ||
(x.isComposite() && x.isLinear()) ||
(g === CB && x.isLinear())
) {
parts[2].push(x);
} else if (g === EX || (x.isComposite() && !x.isLinear()))
parts[4].push(x);
else __.integration.stop();
};
if (symbol.group === CB)
symbol.each(function (x) {
setSymbol(Symbol.unwrapSQRT(x, true));
});
else setSymbol(symbol);
var u,
dv = new Symbol(1);
//compile u and dv
for (var i = 0; i < 5; i++) {
var part = parts[i],
t,
l = part.length;
if (l > 0) {
if (l > 1) {
t = new Symbol(1);
for (var j = 0; j < l; j++) t = _.multiply(t, part[j].clone());
} else t = part[0].clone();
if (!u) {
u = t; //the first u encountered gets chosen
u.multiplier = u.multiplier.multiply(symbol.multiplier); //the first one gets the mutliplier
} else dv = _.multiply(dv, t); //everything else belongs to dv
}
}
return [u, dv];
},
by_parts: function (symbol, dx, depth, o) {
o.previous = o.previous || [];
var udv, u, dv, du, v, vdu, uv, retval, integral_vdu, m, c, vdu_s;
//first LIATE
udv = __.integration.get_udv(symbol);
u = udv[0];
dv = udv[1];
du = Symbol.unwrapSQRT(_.expand(__.diff(u.clone(), dx)), true);
c = du.clone().stripVar(dx);
//strip any coefficients
du = _.divide(du, c.clone());
v = __.integrate(dv.clone(), dx, depth || 0);
vdu = _.multiply(v.clone(), du);
vdu_s = vdu.toString();
//currently only supports e^x*(some trig)
if (
o.previous.indexOf(vdu_s) !== -1 &&
core.Utils.in_trig(u.fname) &&
dv.isE()
) {
//We're going to exploit the fact that vdu can never be constant
//to work out way out of this cycle. We'll return the length of
//the this.previous array until we're back at level one
o.is_cyclic = true;
//return the integral.
return new Symbol(1);
} else o.previous.push(vdu_s);
uv = _.multiply(u, v);
//clear the multiplier so we're dealing with a bare integral
m = vdu.multiplier.clone();
vdu.toUnitMultiplier();
integral_vdu = _.multiply(__.integrate(vdu.clone(), dx, depth, o), c);
integral_vdu.multiplier = integral_vdu.multiplier.multiply(m);
retval = _.subtract(uv, integral_vdu);
//we know that there cannot be constants so they're a holdover from a cyclic integral
if (o.is_cyclic) {
//start popping the previous stack so we know how deep in we are
o.previous.pop();
if (o.previous.length === 0) {
retval = _.expand(retval);
var rem = new Symbol(0);
retval.each(function (x) {
if (!x.contains(dx)) rem = _.add(rem, x.clone());
});
//get the actual uv
retval = _.divide(
_.subtract(retval, rem.clone()),
_.subtract(new Symbol(1), rem)
);
}
}
return retval;
},
/*
* dependents: [Solve, integrate]
*/
decompose_arg: function (arg, dx) {
var ax, a, x, b;
if (arg.group === CP) {
var t = _.expand(arg.clone()).stripVar(dx);
ax = _.subtract(arg.clone(), t.clone());
b = t;
} else ax = arg.clone();
a = ax.stripVar(dx);
x = _.divide(ax.clone(), a.clone());
return [a, x, ax, b];
}
},
//TODO: nerdamer.integrate('-e^(-a*t)*sin(t)', 't') -> gives incorrect output
integrate: function (original_symbol, dt, depth, opt) {
//assume integration wrt independent variable if expression only has one variable
if (!dt) {
var vars = core.Utils.variables(original_symbol);
if (vars.length === 1) dt = vars[0];
}
//add support for integrating vectors
if (core.Utils.isVector(original_symbol)) {
var vector = new core.Vector([]);
original_symbol.each(function (x) {
vector.elements.push(__.integrate(x, dt));
});
return vector;
}
if (!isNaN(dt)) _.error("variable expected but received " + dt);
//configurations options for integral. This is needed for tracking extra options
//e.g. cyclic integrals or additional settings
opt = opt || {};
return core.Utils.block(
"PARSE2NUMBER",
function () {
//make a note of the original symbol. Set only if undefined
depth = depth || 0;
var dx = isSymbol(dt) ? dt.toString() : dt,