-
Notifications
You must be signed in to change notification settings - Fork 0
/
algebra.js
4553 lines (4136 loc) · 192 KB
/
algebra.js
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
/*
* Author : Martin Donk
* Website : http://www.nerdamer.com
* Email : martin.r.donk@gmail.com
* License : MIT
* Source : https://github.com/jiggzson/nerdamer
*/
/* global module, Function */
if((typeof module) !== 'undefined') {
var nerdamer = require('./nerdamer.core.js');
require('./Calculus.js');
}
(function () {
"use strict";
/*shortcuts*/
var core = nerdamer.getCore(),
_ = core.PARSER,
N = core.groups.N,
P = core.groups.P,
S = core.groups.S,
EX = core.groups.EX,
FN = core.groups.FN,
PL = core.groups.PL,
CP = core.groups.CP,
CB = core.groups.CB,
keys = core.Utils.keys,
even = core.Utils.even,
variables = core.Utils.variables,
format = core.Utils.format,
round = core.Utils.round,
Frac = core.Frac,
isInt = core.Utils.isInt,
Symbol = core.Symbol,
CONST_HASH = core.Settings.CONST_HASH,
math = core.Utils.importFunctions(),
evaluate = core.Utils.evaluate;
//*************** CLASSES ***************//
/**
* Converts a symbol into an equivalent polynomial arrays of
* the form [[coefficient_1, power_1],[coefficient_2, power_2], ... ]
* Univariate polymials only.
* @param {Symbol|Number} symbol
* @param {String} variable The variable name of the polynomial
* @param {int} order
*/
function Polynomial(symbol, variable, order) {
if(core.Utils.isSymbol(symbol)) {
this.parse(symbol);
this.variable = this.variable || variable;
}
else if(!isNaN(symbol)) {
order = order || 0;
if(variable === undefined)
throw new core.exceptions.InvalidVariableNameError('Polynomial expects a variable name when creating using order');
this.coeffs = [];
this.coeffs[order] = symbol;
this.fill(symbol);
}
else if(typeof symbol === 'string') {
this.parse(_.parse(symbol));
}
}
/**
* Creates a Polynomial given an array of coefficients
* @param {int[]} arr
* @param {String} variable
* @returns {Polynomial}
*/
Polynomial.fromArray = function (arr, variable) {
if(typeof variable === 'undefined')
throw new core.exceptions.InvalidVariableNameError('A variable name must be specified when creating polynomial from array');
var p = new Polynomial();
p.coeffs = arr;
p.variable = variable;
return p;
};
Polynomial.fit = function (c1, c2, n, base, p, variable) {
//after having looped through and mod 10 the number to get the matching factor
var terms = new Array(p + 1),
t = n - c2;
terms[0] = c2; //the constants is assumed to be correct
//constant for x^p is also assumed know so add
terms[p] = c1;
t -= c1 * Math.pow(base, p);
//start fitting
for(var i = p - 1; i > 0; i--) {
var b = Math.pow(base, i), //we want as many wholes as possible
q = t / b,
sign = Math.sign(q);
var c = sign * Math.floor(Math.abs(q));
t -= c * b;
terms[i] = c;
}
if(t !== 0)
return null;
for(var i = 0; i < terms.length; i++)
terms[i] = new Frac(terms[i]);
return Polynomial.fromArray(terms, variable);
};
Polynomial.prototype = {
/**
* Converts Symbol to Polynomial
* @param {Symbol} symbol
* @param {Array} c - a collector array
* @returns {Polynomial}
*/
parse: function (symbol, c) {
this.variable = variables(symbol)[0];
if(!symbol.isPoly())
throw core.exceptions.NerdamerTypeError('Polynomial Expected! Received ' + core.Utils.text(symbol));
c = c || [];
if(!symbol.power.absEquals(1))
symbol = _.expand(symbol);
if(symbol.group === core.groups.N) {
c[0] = symbol.multiplier;
}
else if(symbol.group === core.groups.S) {
c[symbol.power.toDecimal()] = symbol.multiplier;
}
else {
for(var x in symbol.symbols) {
var sub = symbol.symbols[x],
p = sub.power;
if(core.Utils.isSymbol(p))
throw new core.exceptions.NerdamerTypeError('power cannot be a Symbol');
p = sub.group === N ? 0 : p.toDecimal();
if(sub.symbols) {
this.parse(sub, c);
}
else {
c[p] = sub.multiplier;
}
}
}
this.coeffs = c;
this.fill();
},
/**
* Fills in the holes in a polynomial with zeroes
* @param {Number} x - The number to fill the holes with
*/
fill: function (x) {
x = Number(x) || 0;
var l = this.coeffs.length;
for(var i = 0; i < l; i++) {
if(this.coeffs[i] === undefined) {
this.coeffs[i] = new Frac(x);
}
}
return this;
},
/**
* Removes higher order zeros or a specific coefficient
* @returns {Array}
*/
trim: function () {
var l = this.coeffs.length;
while(l--) {
var c = this.coeffs[l];
var equalsZero = c.equals(0);
if(c && equalsZero) {
if(l === 0)
break;
this.coeffs.pop();
}
else
break;
}
return this;
},
/*
* Returns polynomial mod p **currently fails**
* @param {Number} p
* @returns {Polynomial}
*/
modP: function (p) {
var l = this.coeffs.length;
for(var i = 0; i < l; i++) {
var c = this.coeffs[i];
if(c < 0) { //go borrow
var b; //a coefficient > 0
for(var j = i; j < l; j++) {//starting from where we left off
if(this.coeffs[j] > 0) {
b = this.coeffs[j];
break;
}
}
if(b) { //if such a coefficient exists
for(j; j > i; j--) { //go down the line and adjust using p
this.coeffs[j] = this.coeffs[j].subtract(new Frac(1));
this.coeffs[j - 1] = this.coeffs[j - 1].add(new Frac(p));
}
c = this.coeffs[i]; //reset c
}
}
var d = c.mod(p);
var w = c.subtract(d).divide(p);
if(!w.equals(0)) {
var up_one = i + 1;
var next = this.coeffs[up_one] || new Frac(0);
next = next.add(w);
this.coeffs[up_one] = new Frac(next);
this.coeffs[i] = new Frac(d);
}
}
return this;
},
/**
* Adds together 2 polynomials
* @param {Polynomial} poly
*/
add: function (poly) {
var l = Math.max(this.coeffs.length, poly.coeffs.length);
for(var i = 0; i < l; i++) {
var a = (this.coeffs[i] || new Frac(0)),
b = (poly.coeffs[i] || new Frac(0));
this.coeffs[i] = a.add(b);
}
return this;
},
/**
* Adds together 2 polynomials
* @param {Polynomial} poly
*/
subtract: function (poly) {
var l = Math.max(this.coeffs.length, poly.coeffs.length);
for(var i = 0; i < l; i++) {
var a = (this.coeffs[i] || new Frac(0)),
b = (poly.coeffs[i] || new Frac(0));
this.coeffs[i] = a.subtract(b);
}
return this;
},
divide: function (poly) {
var variable = this.variable,
dividend = core.Utils.arrayClone(this.coeffs),
divisor = core.Utils.arrayClone(poly.coeffs),
n = dividend.length,
mp = divisor.length - 1,
quotient = [];
//loop through the dividend
for(var i = 0; i < n; i++) {
var p = n - (i + 1);
//get the difference of the powers
var d = p - mp;
//get the quotient of the coefficients
var q = dividend[p].divide(divisor[mp]);
if(d < 0)
break;//the divisor is not greater than the dividend
//place it in the quotient
quotient[d] = q;
for(var j = 0; j <= mp; j++) {
//reduce the dividend
dividend[j + d] = dividend[j + d].subtract((divisor[j].multiply(q)));
}
}
//clean up
var p1 = Polynomial.fromArray(dividend, variable || 'x').trim(), //pass in x for safety
p2 = Polynomial.fromArray(quotient, variable || 'x');
return [p2, p1];
},
multiply: function (poly) {
var l1 = this.coeffs.length, l2 = poly.coeffs.length,
c = []; //array to be returned
for(var i = 0; i < l1; i++) {
var x1 = this.coeffs[i];
for(var j = 0; j < l2; j++) {
var k = i + j, //add the powers together
x2 = poly.coeffs[j],
e = c[k] || new Frac(0); //get the existing term from the new array
c[k] = e.add(x1.multiply(x2)); //multiply the coefficients and add to new polynomial array
}
}
this.coeffs = c;
return this;
},
/**
* Checks if a polynomial is zero
* @returns {Boolean}
*/
isZero: function () {
var l = this.coeffs.length;
for(var i = 0; i < l; i++) {
var e = this.coeffs[i];
if(!e.equals(0))
return false;
}
return true;
},
/**
* Substitutes in a number n into the polynomial p(n)
* @param {Number} n
* @returns {Frac}
*/
sub: function (n) {
var sum = new Frac(0), l = this.coeffs.length;
for(var i = 0; i < l; i++) {
var t = this.coeffs[i];
if(!t.equals(0))
sum = sum.add(t.multiply(new Frac(Math.pow(n, i))));
}
return sum;
},
/**
* Returns a clone of the polynomial
* @returns {Polynomial}
*/
clone: function () {
var p = new Polynomial();
p.coeffs = this.coeffs;
p.variable = this.variable;
return p;
},
/**
* Gets the degree of the polynomial
* @returns {Number}
*/
deg: function () {
this.trim();
return this.coeffs.length - 1;
},
/**
* Returns a lead coefficient
* @returns {Frac}
*/
lc: function () {
return this.coeffs[this.deg()].clone();
},
/**
* Converts polynomial into a monic polynomial
* @returns {Polynomial}
*/
monic: function () {
var lc = this.lc(), l = this.coeffs.length;
for(var i = 0; i < l; i++)
this.coeffs[i] = this.coeffs[i].divide(lc);
return this;
},
/**
* Returns the GCD of two polynomials
* @param {Polynomial} poly
* @returns {Polynomial}
*/
gcd: function (poly) {
//get the maximum power of each
var mp1 = this.coeffs.length - 1,
mp2 = poly.coeffs.length - 1,
T;
//swap so we always have the greater power first
if(mp1 < mp2) {
return poly.gcd(this);
}
var a = this;
while(!poly.isZero()) {
var t = poly.clone();
a = a.clone();
T = a.divide(t);
poly = T[1];
a = t;
}
var gcd = core.Math2.QGCD.apply(null, a.coeffs);
if(!gcd.equals(1)) {
var l = a.coeffs.length;
for(var i = 0; i < l; i++) {
a.coeffs[i] = a.coeffs[i].divide(gcd);
}
}
return a;
},
/**
* Differentiates the polynomial
* @returns {Polynomial}
*/
diff: function () {
var new_array = [], l = this.coeffs.length;
for(var i = 1; i < l; i++)
new_array.push(this.coeffs[i].multiply(new Frac(i)));
this.coeffs = new_array;
return this;
},
/**
* Integrates the polynomial
* @returns {Polynomial}
*/
integrate: function () {
var new_array = [0], l = this.coeffs.length;
for(var i = 0; i < l; i++) {
var c = new Frac(i + 1);
new_array[c] = this.coeffs[i].divide(c);
}
this.coeffs = new_array;
return this;
},
/**
* Returns the Greatest common factor of the polynomial
* @param {bool} toPolynomial - true if a polynomial is wanted
* @returns {Frac|Polynomial}
*/
gcf: function (toPolynomial) {
//get the first nozero coefficient and returns its power
var fnz = function (a) {
for(var i = 0; i < a.length; i++)
if(!a[i].equals(0))
return i;
},
ca = [];
for(var i = 0; i < this.coeffs.length; i++) {
var c = this.coeffs[i];
if(!c.equals(0) && ca.indexOf(c) === -1)
ca.push(c);
}
var p = [core.Math2.QGCD.apply(undefined, ca), fnz(this.coeffs)].toDecimal();
if(toPolynomial) {
var parr = [];
parr[p[1] - 1] = p[0];
p = Polynomial.fromArray(parr, this.variable).fill();
}
return p;
},
/**
* Raises a polynomial P to a power p -> P^p. e.g. (x+1)^2
* @param {bool} incl_img - Include imaginary numbers
*/
quad: function (incl_img) {
var roots = [];
if(this.coeffs.length > 3)
throw new Error('Cannot calculate quadratic order of ' + (this.coeffs.length - 1));
if(this.coeffs.length === 0)
throw new Error('Polynomial array has no terms');
var a = this.coeffs[2] || 0, b = this.coeffs[1] || 0, c = this.coeffs[0];
var dsc = b * b - 4 * a * c;
if(dsc < 0 && !incl_img)
return roots;
else {
roots[0] = (-b + Math.sqrt(dsc)) / (2 * a);
roots[1] = (-b - Math.sqrt(dsc)) / (2 * a);
}
return roots;
},
/**
* Makes polynomial square free
* @returns {Array}
*/
squareFree: function () {
var a = this.clone(),
i = 1,
b = a.clone().diff(),
c = a.clone().gcd(b),
w = a.divide(c)[0];
var output = Polynomial.fromArray([new Frac(1)], a.variable);
while(!c.equalsNumber(1)) {
var y = w.gcd(c);
var z = w.divide(y)[0];
//one of the factors may have shown up since it's square but smaller than the
//one where finding
if(!z.equalsNumber(1) && i > 1) {
var t = z.clone();
for(var j = 1; j < i; j++)
t.multiply(z.clone());
z = t;
}
output = output.multiply(z);
i++;
w = y;
c = c.divide(y)[0];
}
return [output, w, i];
},
/**
* Converts polynomial to Symbol
* @returns {Symbol}
*/
toSymbol: function () {
var l = this.coeffs.length,
variable = this.variable;
if(l === 0)
return new core.Symbol(0);
var end = l - 1, str = '';
for(var i = 0; i < l; i++) {
//place the plus sign for all but the last one
var plus = i === end ? '' : '+',
e = this.coeffs[i];
if(!e.equals(0))
str += (e + '*' + variable + '^' + i + plus);
}
return _.parse(str);
},
/**
* Checks if polynomial is equal to a number
* @param {Number} x
* @returns {Boolean}
*/
equalsNumber: function (x) {
this.trim();
return this.coeffs.length === 1 && this.coeffs[0].toDecimal() === String(x);
},
toString: function () {
return this.toSymbol().toString();
}
};
/**
* TODO
* ===================================================================================
* THIS METHOD HAS A NASTY HIDDEN BUG. IT HAS INCONSISTENT RETURN TYPES PRIMARILY DUE TO
* WRONG ASSUMPTIONS AT THE BEGINNING. THE ASSUMPTION WAS THAT COEFFS WERE ALWAYS GOING BE NUMBERS
* NOT TAKING INTO ACCOUNT THAT IMAGINARY NUMBERS. FIXING THIS BREAKS WAY TOO MANY TESTS
* AT THEM MOMENT WHICH I DON'T HAVE TO FIX
* ===================================================================================
* If the symbols is of group PL or CP it will return the multipliers of each symbol
* as these are polynomial coefficients. CB symbols are glued together by multiplication
* so the symbol multiplier carries the coefficients for all contained symbols.
* For S it just returns it's own multiplier. This function doesn't care if it's a polynomial or not
* @param {Array} c The coefficient array
* @param {boolean} with_order
* @return {Array}
*/
Symbol.prototype.coeffs = function (c, with_order) {
if(with_order && !this.isPoly(true))
_.error('Polynomial expected when requesting coefficients with order');
c = c || [];
var s = this.clone().distributeMultiplier();
if(s.isComposite()) {
for(var x in s.symbols) {
var sub = s.symbols[x];
if(sub.isComposite()) {
sub.clone().distributeMultiplier().coeffs(c, with_order);
}
else {
if(with_order)
c[sub.isConstant() ? 0 : sub.power.toDecimal()] = sub.multiplier;
else {
c.push(sub.multiplier);
}
}
}
}
else {
if(with_order)
c[s.isConstant(true) ? 0 : s.power.toDecimal()] = s.multiplier;
else {
if(s.group === CB && s.isImaginary()) {
var m = new Symbol(s.multiplier);
s.each(function (x) {
//add the imaginary part
if(x.isConstant(true) || x.imaginary)
m = _.multiply(m, x);
});
c.push(m);
}
else
c.push(s.multiplier);
}
}
//fill the holes
if(with_order) {
for(var i = 0; i < c.length; i++)
if(c[i] === undefined)
c[i] = new Symbol(0);
}
return c;
};
Symbol.prototype.tBase = function (map) {
if(typeof map === 'undefined')
throw new Error('Symbol.tBase requires a map object!');
var terms = [];
var symbols = this.collectSymbols(null, null, null, true),
l = symbols.length;
for(var i = 0; i < l; i++) {
var symbol = symbols[i],
g = symbol.group,
nterm = new MVTerm(symbol.multiplier, [], map);
if(g === CB) {
for(var x in symbol.symbols) {
var sym = symbol.symbols[x];
nterm.terms[map[x]] = sym.power;
}
}
else {
nterm.terms[map[symbol.value]] = symbol.power;
}
terms.push(nterm.fill());
nterm.updateCount();
}
return terms;
};
Symbol.prototype.altVar = function (x) {
var m = this.multiplier.toString(), p = this.power.toString();
return (m === '1' ? '' : m + '*') + x + (p === '1' ? '' : '^' + p);
};
/**
* Checks to see if the symbols contain the same variables
* @param {Symbol} symbol
* @returns {Boolean}
*/
Symbol.prototype.sameVars = function (symbol) {
if(!(this.symbols || this.group === symbol.group))
return false;
for(var x in this.symbols) {
var a = this.symbols[x], b = symbol.symbols[x];
if(!b)
return false;
if(a.value !== b.value)
return false;
}
return true;
};
/**
* Groups the terms in a symbol with respect to a variable
* For instance the symbol {a*b^2*x^2+a*b*x^2+x+6} returns [6,1,a*b+a*b^2]
* @returns {Factors}
*/
Symbol.prototype.groupTerms = function (x) {
x = String(x);
var f, p, egrouped;
var grouped = [];
this.each(function (e) {
if(e.group === PL) {
egrouped = e.groupTerms(x);
for(var i = 0; i < egrouped.length; i++) {
var el = egrouped[i];
if(el)
grouped[i] = el;
}
}
else {
f = core.Utils.decompose_fn(e, x, true);
p = f.x.value === x ? Number(f.x.power) : 0;
//check if there's an existing value
grouped[p] = _.add(grouped[p] || new Symbol(0), f.a);
}
});
return grouped;
};
/**
* Use this to collect Factors
* @returns {Symbol[]}
*/
Symbol.prototype.collectFactors = function () {
var factors = [];
if(this.group === CB)
this.each(function (x) {
factors.push(x.clone());
});
else
factors.push(this.clone());
return factors;
};
/**
* A container class for factors
* @returns {Factors}
*/
function Factors() {
this.factors = {};
this.length = 0;
}
;
Factors.prototype.getNumberSymbolics = function () {
var n = 0;
this.each(function (x) {
if(!x.isConstant(true))
n++;
});
return n;
};
/**
* Adds the factors to the factor object
* @param {Symbo} s
* @returns {Factors}
*/
Factors.prototype.add = function (s) {
if(s.equals(0))
return this; //nothing to add
//we don't want to carry -1 as a factor. If a factor already exists,
//then add the minus one to that factor and return.
if(s.equals(-1) && this.length > 0) {
var fo = core.Utils.firstObject(this.factors, null, true);
this.add(_.symfunction(core.Settings.PARENTHESIS, [fo.obj]).negate());
delete this.factors[fo.key];
this.length--;
return this;
}
if(s.group === CB) {
var factors = this;
if(!s.multiplier.equals(1))
factors.add(new Symbol(s.multiplier));
s.each(function (x) {
factors.add(x);
});
}
else {
if(this.preAdd) //if a preAdd function was defined call it to do prep
s = this.preAdd(s);
if(this.pFactor) //if the symbol isn't linear add back the power
s = _.pow(s, new Symbol(this.pFactor));
var is_constant = s.isConstant();
if(is_constant && s.equals(1))
return this; //don't add 1
var v = is_constant ? s.value : s.text();
if(v in this.factors) {
this.factors[v] = _.multiply(this.factors[v], s);
//did the addition cancel out the existing factor? If so remove it and decrement the length
if(this.factors[v].equals(1)) {
delete this.factors[v];
this.length--;
}
}
else {
this.factors[v] = s;
this.length++;
}
}
return this;
};
/**
* Converts the factor object to a Symbol
* @returns {Symbol}
*/
Factors.prototype.toSymbol = function () {
var factored = new Symbol(1);
var factors = Object.values(this.factors).sort(function (a, b) {
return a.group > b.group;
});
for(var i = 0, l = factors.length; i < l; i++) {
var f = factors[i];
//don't wrap group S or FN
var factor = f.power.equals(1) && f.fname !== '' /* don't wrap it twice */ ?
_.symfunction(core.PARENTHESIS, [f]) : f;
factored = _.multiply(factored, factor);
}
if(factored.fname === '')
factored = Symbol.unwrapPARENS(factored);
return factored;
};
/**
* Merges 2 factor objects into one
* @param {Factor} o
* @returns {Factors}
*/
Factors.prototype.merge = function (o) {
for(var x in o) {
if(x in this.factors)
this.factors[x] = _.multiply(this.factors[x], o[x]);
else
this.factors[x] = o[x];
}
return this;
};
/**
* The iterator for the factor object
* @param {Function} f - callback
* @returns {Factor}
*/
Factors.prototype.each = function (f) {
for(var x in this.factors) {
var factor = this.factors[x];
if(factor.fname === core.PARENTHESIS && factor.isLinear())
factor = factor.args[0];
f.call(this, factor, x);
}
return this;
};
/**
* Return the number of factors contained in the factor object
* @returns {int}
*/
Factors.prototype.count = function () {
return keys(this.factors).length;
};
/**
* Cleans up factors from -1
* @returns {undefined}
*/
Factors.prototype.clean = function () {
try {
var h = core.Settings.CONST_HASH;
if(this.factors[h].lessThan(0)) {
if(this.factors[h].equals(-1))
delete this.factors[h];
else
this.factors[h].negate();
this.each(function (x) {
x.negate();
});
}
}
catch(e) {
}
;
};
Factors.prototype.toString = function () {
return this.toSymbol().toString();
};
//a wrapper for performing multivariate division
function MVTerm(coeff, terms, map) {
this.terms = terms || [];
this.coeff = coeff;
this.map = map; //careful! all maps are the same object
this.sum = new core.Frac(0);
this.image = undefined;
}
;
MVTerm.prototype.updateCount = function () {
this.count = this.count || 0;
for(var i = 0; i < this.terms.length; i++) {
if(!this.terms[i].equals(0))
this.count++;
}
return this;
};
MVTerm.prototype.getVars = function () {
var vars = [];
for(var i = 0; i < this.terms.length; i++) {
var term = this.terms[i],
rev_map = this.getRevMap();
if(!term.equals(0))
vars.push(this.rev_map[i]);
}
return vars.join(' ');
};
MVTerm.prototype.len = function () {
if(typeof this.count === 'undefined') {
this.updateCount();
}
return this.count;
};
MVTerm.prototype.toSymbol = function (rev_map) {
rev_map = rev_map || this.getRevMap();
var symbol = new Symbol(this.coeff);
for(var i = 0; i < this.terms.length; i++) {
var v = rev_map[i],
t = this.terms[i];
if(t.equals(0) || v === CONST_HASH)
continue;
var mapped = new Symbol(v);
mapped.power = t;
symbol = _.multiply(symbol, mapped);
}
return symbol;
};
MVTerm.prototype.getRevMap = function () {
if(this.rev_map)
return this.rev_map;
var o = {};
for(var x in this.map)
o[this.map[x]] = x;
this.rev_map = o;
return o;
};
MVTerm.prototype.generateImage = function () {
this.image = this.terms.join(' ');
return this;
},
MVTerm.prototype.getImg = function () {
if(!this.image)
this.generateImage();
return this.image;
},
MVTerm.prototype.fill = function () {
var l = this.map.length;
for(var i = 0; i < l; i++) {
if(typeof this.terms[i] === 'undefined')
this.terms[i] = new core.Frac(0);
else {
this.sum = this.sum.add(this.terms[i]);
}
}
return this;
};
MVTerm.prototype.divide = function (mvterm) {
var c = this.coeff.divide(mvterm.coeff),
l = this.terms.length,
new_mvterm = new MVTerm(c, [], this.map);
for(var i = 0; i < l; i++) {
new_mvterm.terms[i] = this.terms[i].subtract(mvterm.terms[i]);
new_mvterm.sum = new_mvterm.sum.add(new_mvterm.terms[i]);
}
return new_mvterm;
};
MVTerm.prototype.multiply = function (mvterm) {
var c = this.coeff.multiply(mvterm.coeff),
l = this.terms.length,
new_mvterm = new MVTerm(c, [], this.map);
for(var i = 0; i < l; i++) {
new_mvterm.terms[i] = this.terms[i].add(mvterm.terms[i]);
new_mvterm.sum = new_mvterm.sum.add(new_mvterm.terms[i]);
}
return new_mvterm;
};
MVTerm.prototype.isZero = function () {
return this.coeff.equals(0);
};
MVTerm.prototype.toString = function () {
return '{ coeff: ' + this.coeff.toString() + ', terms: [' +
this.terms.join(',') + ']: sum: ' + this.sum.toString() + ', count: ' + this.count + '}';
};
core.Utils.toMapObj = function (arr) {
var c = 0, o = {};
for(var i = 0; i < arr.length; i++) {
var v = arr[i];
if(typeof o[v] === 'undefined') {
o[v] = c;
c++;
}
}
o.length = c;
return o;
};
core.Utils.filledArray = function (v, n, clss) {
var a = [];
while(n--) {
a[n] = clss ? new clss(v) : v;
}
return a;
};
core.Utils.arrSum = function (arr) {
var sum = 0, l = arr.length;
for(var i = 0; i < l; i++)
sum += arr[i];
return sum;
};
/**
* Determines if 2 arrays have intersecting elements.
* @param {Array} a
* @param {Array} b
* @returns {Boolean} True if a and b have intersecting elements.
*/
core.Utils.haveIntersection = function (a, b) {
var t;
if(b.length > a.length)
t = b, b = a, a = t; // indexOf to loop over shorter
return a.some(function (e) {
return b.indexOf(e) > -1;
});
};
/**
* Substitutes out functions as variables so they can be used in regular algorithms
* @param {Symbol} symbol
* @param {Object} map
* @returns {String} The expression string
*/
core.Utils.subFunctions = function (symbol, map) {
map = map || {};
var subbed = [];
symbol.each(function (x) {
if(x.group === FN || x.previousGroup === FN) {
//we need a new variable name so why not use one of the existing
var val = core.Utils.text(x, 'hash'), tvar = map[val];
if(!tvar) {
//generate a unique enough name
var t = x.fname + keys(map).length;
map[val] = t;
subbed.push(x.altVar(t));
}
else
subbed.push(x.altVar(tvar));
}
else if(x.group === CB || x.group === PL || x.group === CP) {
subbed.push(core.Utils.subFunctions(x, map));
}
else
subbed.push(x.text());
});
if(symbol.group === CP || symbol.group === PL)
return symbol.altVar(core.Utils.inBrackets(subbed.join('+')));