forked from jiggzson/nerdamer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlgebra.js
1764 lines (1574 loc) · 77.9 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
*/
if((typeof module) !== 'undefined') {
nerdamer = require('./nerdamer.core.js');
}
(function() {
"use strict";
/*shortcuts*/
var core = nerdamer.getCore(),
_ = core.PARSER,
N = core.groups.N,
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,
variables = core.Utils.variables,
round = core.Utils.round,
Frac = core.Frac,
isInt = core.Utils.isInt,
Symbol = core.Symbol,
EPSILON = core.Settings.EPSILON;
/**
* Converts a symbol into an equivalent polynomial arrays of
* the form [[coefficient_1, power_1],[coefficient_2, power_2], ... ]
* @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);
}
else if(!isNaN(symbol)) {
order = order || 0;
if(variable === undefined)
throw new Error('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));
}
}
Polynomial.fromArray = function(arr, variable) {
if(typeof variable === 'undefined')
throw new Error('A variable name must be specified when creating polynomial from array');
var p = new Polynomial();
p.coeffs = arr;
p.variable = variable;
return p;
};
Polynomial.prototype = {
parse: function(symbol, c) {
this.variable = variables(symbol)[0];
if(!symbol.isPoly()) throw new Error('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 Error('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];
if(c && c.equals(0)) this.coeffs.pop();
else break;
}
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;
var inBrackets = core.Utils.inBrackets;
//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;
},
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;
},
clone: function() {
var p = new Polynomial();
p.coeffs = this.coeffs;
p.variable = this.variable;
return p;
},
deg: function() {
this.trim();
return this.coeffs.length-1;
},
lc: function() {
return this.coeffs[this.deg()].clone();
},
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;
},
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;
},
polyGCD: function(poly) {
},
/**
* Differentiates the 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
*/
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;
},
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 {Int} p - The power to be raised to
*
raiseTo: function(p) {
var a = this.coeffs.slice(), ll=this.coeffs.length;
while(--p) {
var l = a.length, r=[];
for(var i=0; i<l; i++) {
for(var j=0; j<ll; j++) {
var idx = i+j, e = r[idx] || 0;
r[idx] = e+a[i]*this.coeffs[j];
}
}
a = r;
}
this.coeffs = r;
return this;
},*/
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;
},
/**
* 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);
},
equalsNumber: function(x) {
this.trim();
return this.coeffs.length === 1 && this.coeffs[0] === x;
},
toString: function() {
return this.toSymbol().toString();
}
};
//make the polynomial class available to EVERYONE!
core.Polynomial = Polynomial;
/**
* 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
* @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() ? 0 : s.power.toDecimal()] = s.multiplier;
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 Frac(0);
}
return c;
};
Symbol.LSORT = function(a, b) {
if(a.value === b.value && a.multiplier > b.multiplier) return b.power - a.power;
return (a.length || 1) - (b.length || 1);
};
Symbol.prototype.altVar = function(x) {
var m = this.multiplier.toString(), p = this.power.toString();
return (m === '1' ? '' : m+'*')+ x + (p === '1' ? '' : '^'+p);
};
Symbol.prototype.hasFunc = function() {
if(this.group === FN || this.group === EX) return true;
if(this.symbols) {
for(var x in this.symbols) {
if(this.symbols[x].hasFunc()) return true;
}
}
return false;
};
Symbol.prototype.hasConstant = function() {
if(this.group === CP) {
for(var x in this.symbols) {
if(this.symbols[x].isConstant()) return true;
}
}
return false;
};
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+core.Utils.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('+')));;
if(symbol.group === CB) return symbol.altVar(core.Utils.inBrackets(subbed.join('*')));
return symbol.text();
};
/**
* A debugging method to be stripped
* @returns {String}
*/
var qc = function() {
var args = [].slice.call(arguments),
name = args.shift();
args = args.map(function(a) {
return __.polyArray2Symbol(a, 'x').text();
});
return name+'('+args.join(',')+')';
};
var __ = core.Algebra = {
version: '1.3.3',
init: (function() {})(),
proots: function(symbol, decp) {
//the roots will be rounded up to 7 decimal places.
//if this causes trouble you can explicitly pass in a different number of places
//rarr for polynomial of power n is of format [n, coeff x^n, coeff x^(n-1), ..., coeff x^0]
decp = decp || 7;
var zeros = 0;
var get_roots = function(rarr, powers, max) {
var roots = calcroots(rarr, powers, max);
for(var i=0;i<zeros;i++) roots.unshift(0);
return roots;
};
if(symbol instanceof Symbol && symbol.isPoly()) {
if(symbol.group === core.groups.S) {
return [0];
}
else if(symbol.group === core.groups.PL) {
var powers = keys(symbol.symbols),
minpower = core.Utils.arrayMin(powers),
symbol = core.PARSER.divide(symbol, core.PARSER.parse(symbol.value+'^'+minpower));
}
var variable = keys(symbol.symbols).sort().pop(),
sym = symbol.group === core.groups.PL ? symbol.symbols : symbol.symbols[variable],
g = sym.group,
powers = g === S ? [sym.power.toDecimal()] : keys(sym.symbols),
rarr = [],
max = core.Utils.arrayMax(powers); //maximum power and degree of polynomial to be solved
// Prepare the data
for(var i=1; i<=max; i++) {
var c = 0; //if there is no power then the hole must be filled with a zero
if(powers.indexOf(i+'') !== -1) {
if(g === S) {
c = sym.multiplier;
}
else {
c = sym.symbols[i].multiplier;
}
}
// Insert the coeffient but from the front
rarr.unshift(c);
}
rarr.push(symbol.symbols['#'].multiplier);
if(sym.group === S) rarr[0] = sym.multiplier;//the symbol maybe of group CP with one variable
return get_roots(rarr, powers, max);
}
else if(core.Utils.isArray(symbol)) {
var parr = symbol;
var rarr = [],
powers = [],
last_power = 0;
for(var i=0; i<parr.length; i++) {
var coeff = parr[i][0],
pow = parr[i][1],
d = pow - last_power - 1;
//insert the zeros
for(var j=0; j<d; j++) rarr.unshift(0);
rarr.unshift(coeff);
if(pow !== 0) powers.push(pow);
last_power = pow;
}
var max = Math.max.apply(undefined, powers);
return get_roots(rarr, powers, max);
}
else {
throw new Error('Cannot calculate roots. Symbol must be a polynomial!');
}
function calcroots(rarr, powers, max){
var MAXDEGREE = 100; // Degree of largest polynomial accepted by this script.
// Make a clone of the coefficients before appending the max power
var p = rarr.slice(0);
// Divide the string up into its individual entries, which--presumably--are separated by whitespace
rarr.unshift(max);
if (max > MAXDEGREE){
throw new Error("This utility accepts polynomials of degree up to " + MAXDEGREE + ". ");
}
var zeroi = [], // Vector of imaginary components of roots
degreePar = {}; // degreePar is a dummy variable for passing the parameter POLYDEGREE by reference
degreePar.Degree = max;
for (i = 0; i < max; i++) {
zeroi.push(0);
}
var zeror = zeroi.slice(0); // Vector of real components of roots
// Find the roots
//--> Begin Jenkins-Traub
/*
* A verbatim copy of Mr. David Binner's Jenkins-Traub port
*/
function QuadSD_ak1(NN, u, v, p, q, iPar){
// Divides p by the quadratic 1, u, v placing the quotient in q and the remainder in a, b
// iPar is a dummy variable for passing in the two parameters--a and b--by reference
q[0] = iPar.b = p[0];
q[1] = iPar.a = -(u*iPar.b) + p[1];
for (var i = 2; i < NN; i++){
q[i] = -(u*iPar.a + v*iPar.b) + p[i];
iPar.b = iPar.a;
iPar.a = q[i];
}
return;
}
function calcSC_ak1(DBL_EPSILON, N, a, b, iPar, K, u, v, qk){
// This routine calculates scalar quantities used to compute the next K polynomial and
// new estimates of the quadratic coefficients.
// calcSC - integer variable set here indicating how the calculations are normalized
// to avoid overflow.
// iPar is a dummy variable for passing in the nine parameters--a1, a3, a7, c, d, e, f, g, and h --by reference
// sdPar is a dummy variable for passing the two parameters--c and d--into QuadSD_ak1 by reference
var sdPar = new Object(),
// TYPE = 3 indicates the quadratic is almost a factor of K
dumFlag = 3;
// Synthetic division of K by the quadratic 1, u, v
sdPar.b = sdPar.a = 0.0;
QuadSD_ak1(N, u, v, K, qk, sdPar);
iPar.c = sdPar.a;
iPar.d = sdPar.b;
if (Math.abs(iPar.c) <= (100.0*DBL_EPSILON*Math.abs(K[N - 1]))) {
if (Math.abs(iPar.d) <= (100.0*DBL_EPSILON*Math.abs(K[N - 2]))) return dumFlag;
}
iPar.h = v*b;
if (Math.abs(iPar.d) >= Math.abs(iPar.c)){
// TYPE = 2 indicates that all formulas are divided by d
dumFlag = 2;
iPar.e = a/(iPar.d);
iPar.f = (iPar.c)/(iPar.d);
iPar.g = u*b;
iPar.a3 = (iPar.e)*((iPar.g) + a) + (iPar.h)*(b/(iPar.d));
iPar.a1 = -a + (iPar.f)*b;
iPar.a7 = (iPar.h) + ((iPar.f) + u)*a;
}
else {
// TYPE = 1 indicates that all formulas are divided by c;
dumFlag = 1;
iPar.e = a/(iPar.c);
iPar.f = (iPar.d)/(iPar.c);
iPar.g = (iPar.e)*u;
iPar.a3 = (iPar.e)*a + ((iPar.g) + (iPar.h)/(iPar.c))*b;
iPar.a1 = -(a*((iPar.d)/(iPar.c))) + b;
iPar.a7 = (iPar.g)*(iPar.d) + (iPar.h)*(iPar.f) + a;
}
return dumFlag;
}
function nextK_ak1(DBL_EPSILON, N, tFlag, a, b, iPar, K, qk, qp){
// Computes the next K polynomials using the scalars computed in calcSC_ak1
// iPar is a dummy variable for passing in three parameters--a1, a3, and a7
var temp;
if (tFlag == 3){ // Use unscaled form of the recurrence
K[1] = K[0] = 0.0;
for (var i = 2; i < N; i++) { K[i] = qk[i - 2]; }
return;
}
temp = ((tFlag == 1) ? b : a);
if (Math.abs(iPar.a1) > (10.0*DBL_EPSILON*Math.abs(temp))){
// Use scaled form of the recurrence
iPar.a7 /= iPar.a1;
iPar.a3 /= iPar.a1;
K[0] = qp[0];
K[1] = -(qp[0]*iPar.a7) + qp[1];
for (var i = 2; i < N; i++) K[i] = -(qp[i - 1]*iPar.a7) + qk[i - 2]*iPar.a3 + qp[i];
}
else {
// If a1 is nearly zero, then use a special form of the recurrence
K[0] = 0.0;
K[1] = -(qp[0]*iPar.a7);
for (var i = 2; i < N; i++) { K[i] = -(qp[i - 1]*iPar.a7) + qk[i - 2]*iPar.a3; }
}
return;
}
function newest_ak1(tFlag, iPar, a, a1, a3, a7, b, c, d, f, g, h, u, v, K, N, p){
// Compute new estimates of the quadratic coefficients using the scalars computed in calcSC_ak1
// iPar is a dummy variable for passing in the two parameters--uu and vv--by reference
// iPar.a = uu, iPar.b = vv
var a4, a5, b1, b2, c1, c2, c3, c4, temp;
iPar.b = iPar.a = 0.0;// The quadratic is zeroed
if (tFlag != 3){
if (tFlag != 2){
a4 = a + u*b + h*f;
a5 = c + (u + v*f)*d;
}
else {
a4 = (a + g)*f + h;
a5 = (f + u)*c + v*d;
}
// Evaluate new quadratic coefficients
b1 = -(K[N - 1]/p[N]);
b2 = -(K[N - 2] + b1*p[N - 1])/p[N];
c1 = v*b2*a1;
c2 = b1*a7;
c3 = b1*b1*a3;
c4 = -(c2 + c3) + c1;
temp = -c4 + a5 + b1*a4;
if (temp != 0.0) {
iPar.a = -((u*(c3 + c2) + v*(b1*a1 + b2*a7))/temp) + u;
iPar.b = v*(1.0 + c4/temp);
}
}
return;
}
function Quad_ak1(a, b1, c, iPar){
// Calculates the zeros of the quadratic a*Z^2 + b1*Z + c
// The quadratic formula, modified to avoid overflow, is used to find the larger zero if the
// zeros are real and both zeros are complex. The smaller real zero is found directly from
// the product of the zeros c/a.
// iPar is a dummy variable for passing in the four parameters--sr, si, lr, and li--by reference
var b, d, e;
iPar.sr = iPar.si = iPar.lr = iPar.li = 0.0;
if (a == 0) {
iPar.sr = ((b1 != 0) ? -(c/b1) : iPar.sr);
return;
}
if (c == 0){
iPar.lr = -(b1/a);
return;
}
// Compute discriminant avoiding overflow
b = b1/2.0;
if (Math.abs(b) < Math.abs(c)){
e = ((c >= 0) ? a : -a);
e = -e + b*(b/Math.abs(c));
d = Math.sqrt(Math.abs(e))*Math.sqrt(Math.abs(c));
}
else {
e = -((a/b)*(c/b)) + 1.0;
d = Math.sqrt(Math.abs(e))*(Math.abs(b));
}
if (e >= 0) {
// Real zeros
d = ((b >= 0) ? -d : d);
iPar.lr = (-b + d)/a;
iPar.sr = ((iPar.lr != 0) ? (c/(iPar.lr))/a : iPar.sr);
}
else {
// Complex conjugate zeros
iPar.lr = iPar.sr = -(b/a);
iPar.si = Math.abs(d/a);
iPar.li = -(iPar.si);
}
return;
}
function QuadIT_ak1(DBL_EPSILON, N, iPar, uu, vv, qp, NN, sdPar, p, qk, calcPar, K){
// Variable-shift K-polynomial iteration for a quadratic factor converges only if the
// zeros are equimodular or nearly so.
// iPar is a dummy variable for passing in the five parameters--NZ, lzi, lzr, szi, and szr--by reference
// sdPar is a dummy variable for passing the two parameters--a and b--in by reference
// calcPar is a dummy variable for passing the nine parameters--a1, a3, a7, c, d, e, f, g, and h --in by reference
// qPar is a dummy variable for passing the four parameters--szr, szi, lzr, and lzi--into Quad_ak1 by reference
var qPar = new Object(),
ee, mp, omp, relstp, t, u, ui, v, vi, zm,
i, j = 0, tFlag, triedFlag = 0; // Integer variables
iPar.NZ = 0;// Number of zeros found
u = uu; // uu and vv are coefficients of the starting quadratic
v = vv;
do {
qPar.li = qPar.lr = qPar.si = qPar.sr = 0.0;
Quad_ak1(1.0, u, v, qPar);
iPar.szr = qPar.sr;
iPar.szi = qPar.si;
iPar.lzr = qPar.lr;
iPar.lzi = qPar.li;
// Return if roots of the quadratic are real and not close to multiple or nearly
// equal and of opposite sign.
if (Math.abs(Math.abs(iPar.szr) - Math.abs(iPar.lzr)) > 0.01*Math.abs(iPar.lzr)) break;
// Evaluate polynomial by quadratic synthetic division
QuadSD_ak1(NN, u, v, p, qp, sdPar);
mp = Math.abs(-((iPar.szr)*(sdPar.b)) + (sdPar.a)) + Math.abs((iPar.szi)*(sdPar.b));
// Compute a rigorous bound on the rounding error in evaluating p
zm = Math.sqrt(Math.abs(v));
ee = 2.0*Math.abs(qp[0]);
t = -((iPar.szr)*(sdPar.b));
for (i = 1; i < N; i++) { ee = ee*zm + Math.abs(qp[i]); }
ee = ee*zm + Math.abs(t + sdPar.a);
ee = (9.0*ee + 2.0*Math.abs(t) - 7.0*(Math.abs((sdPar.a) + t) + zm*Math.abs((sdPar.b))))*DBL_EPSILON;
// Iteration has converged sufficiently if the polynomial value is less than 20 times this bound
if (mp <= 20.0*ee){
iPar.NZ = 2;
break;
}
j++;
// Stop iteration after 20 steps
if (j > 20) break;
if (j >= 2){
if ((relstp <= 0.01) && (mp >= omp) && (!triedFlag)){
// A cluster appears to be stalling the convergence. Five fixed shift
// steps are taken with a u, v close to the cluster.
relstp = ((relstp < DBL_EPSILON) ? Math.sqrt(DBL_EPSILON) : Math.sqrt(relstp));
u -= u*relstp;
v += v*relstp;
QuadSD_ak1(NN, u, v, p, qp, sdPar);
for (i = 0; i < 5; i++){
tFlag = calcSC_ak1(DBL_EPSILON, N, sdPar.a, sdPar.b, calcPar, K, u, v, qk);
nextK_ak1(DBL_EPSILON, N, tFlag, sdPar.a, sdPar.b, calcPar, K, qk, qp);
}
triedFlag = 1;
j = 0;
}
}
omp = mp;
// Calculate next K polynomial and new u and v
tFlag = calcSC_ak1(DBL_EPSILON, N, sdPar.a, sdPar.b, calcPar, K, u, v, qk);
nextK_ak1(DBL_EPSILON, N, tFlag, sdPar.a, sdPar.b, calcPar, K, qk, qp);
tFlag = calcSC_ak1(DBL_EPSILON, N, sdPar.a, sdPar.b, calcPar, K, u, v, qk);
newest_ak1(tFlag, sdPar, sdPar.a, calcPar.a1, calcPar.a3, calcPar.a7, sdPar.b, calcPar.c, calcPar.d, calcPar.f, calcPar.g, calcPar.h, u, v, K, N, p);
ui = sdPar.a;
vi = sdPar.b;
// If vi is zero, the iteration is not converging
if (vi != 0){
relstp = Math.abs((-v + vi)/vi);
u = ui;
v = vi;
}
} while (vi != 0);
return;
}
function RealIT_ak1(DBL_EPSILON, iPar, sdPar, N, p, NN, qp, K, qk){
// Variable-shift H-polynomial iteration for a real zero
// sss - starting iterate = sdPar.a
// NZ - number of zeros found = iPar.NZ
// dumFlag - flag to indicate a pair of zeros near real axis, returned to iFlag
var ee, kv, mp, ms, omp, pv, s, t,
dumFlag, i, j, nm1 = N - 1; // Integer variables
iPar.NZ = j = dumFlag = 0;
s = sdPar.a;
for ( ; ; ) {
pv = p[0];
// Evaluate p at s
qp[0] = pv;
for (i = 1; i < NN; i++) { qp[i] = pv = pv*s + p[i]; }
mp = Math.abs(pv);
// Compute a rigorous bound on the error in evaluating p
ms = Math.abs(s);
ee = 0.5*Math.abs(qp[0]);
for (i = 1; i < NN; i++) { ee = ee*ms + Math.abs(qp[i]); }
// Iteration has converged sufficiently if the polynomial value is less than
// 20 times this bound
if (mp <= 20.0*DBL_EPSILON*(2.0*ee - mp)){
iPar.NZ = 1;
iPar.szr = s;
iPar.szi = 0.0;
break;
}
j++;
// Stop iteration after 10 steps
if (j > 10) break;
if (j >= 2){
if ((Math.abs(t) <= 0.001*Math.abs(-t + s)) && (mp > omp)){
// A cluster of zeros near the real axis has been encountered.
// Return with iFlag set to initiate a quadratic iteration.
dumFlag = 1;
iPar.a = s;
break;
} // End if ((fabs(t) <= 0.001*fabs(s - t)) && (mp > omp))
} //End if (j >= 2)
// Return if the polynomial value has increased significantly
omp = mp;
// Compute t, the next polynomial and the new iterate
qk[0] = kv = K[0];
for (i = 1; i < N; i++) { qk[i] = kv = kv*s + K[i]; }
if (Math.abs(kv) > Math.abs(K[nm1])*10.0*DBL_EPSILON){
// Use the scaled form of the recurrence if the value of K at s is non-zero
t = -(pv/kv);
K[0] = qp[0];
for (i = 1; i < N; i++) { K[i] = t*qk[i - 1] + qp[i]; }
}
else {
// Use unscaled form
K[0] = 0.0;
for (i = 1; i < N; i++) K[i] = qk[i - 1];
}
kv = K[0];
for (i = 1; i < N; i++) { kv = kv*s + K[i]; }
t = ((Math.abs(kv) > (Math.abs(K[nm1])*10.0*DBL_EPSILON)) ? -(pv/kv) : 0.0);
s += t;
}
return dumFlag;
}
function Fxshfr_ak1(DBL_EPSILON, MDP1, L2, sr, v, K, N, p, NN, qp, u, iPar){
// Computes up to L2 fixed shift K-polynomials, testing for convergence in the linear or
// quadratic case. Initiates one of the variable shift iterations and returns with the
// number of zeros found.
// L2 limit of fixed shift steps
// iPar is a dummy variable for passing in the five parameters--NZ, lzi, lzr, szi, and szr--by reference
// NZ number of zeros found
var sdPar = new Object(), // sdPar is a dummy variable for passing the two parameters--a and b--into QuadSD_ak1 by reference
calcPar = new Object(),
// calcPar is a dummy variable for passing the nine parameters--a1, a3, a7, c, d, e, f, g, and h --into calcSC_ak1 by reference
qk = new Array(MDP1),
svk = new Array(MDP1),
a, b, betas, betav, oss, ots, otv, ovv, s, ss, ts, tss, tv, tvv, ui, vi, vv,
fflag, i, iFlag = 1, j, spass, stry, tFlag, vpass, vtry; // Integer variables
iPar.NZ = 0;
betav = betas = 0.25;
oss = sr;
ovv = v;
//Evaluate polynomial by synthetic division
sdPar.b = sdPar.a = 0.0;
QuadSD_ak1(NN, u, v, p, qp, sdPar);
a = sdPar.a;
b = sdPar.b;
calcPar.h = calcPar.g = calcPar.f = calcPar.e = calcPar.d = calcPar.c = calcPar.a7 = calcPar.a3 = calcPar.a1 = 0.0;
tFlag = calcSC_ak1(DBL_EPSILON, N, a, b, calcPar, K, u, v, qk);
for (j = 0; j < L2; j++){
fflag = 1;
// Calculate next K polynomial and estimate v
nextK_ak1(DBL_EPSILON, N, tFlag, a, b, calcPar, K, qk, qp);
tFlag = calcSC_ak1(DBL_EPSILON, N, a, b, calcPar, K, u, v, qk);
// Use sdPar for passing in uu and vv instead of defining a brand-new variable.
// sdPar.a = ui, sdPar.b = vi
newest_ak1(tFlag, sdPar, a, calcPar.a1, calcPar.a3, calcPar.a7, b, calcPar.c, calcPar.d, calcPar.f, calcPar.g, calcPar.h, u, v, K, N, p);
ui = sdPar.a;
vv = vi = sdPar.b;
// Estimate s
ss = ((K[N - 1] != 0.0) ? -(p[N]/K[N - 1]) : 0.0);
ts = tv = 1.0;
if ((j != 0) && (tFlag != 3)){
// Compute relative measures of convergence of s and v sequences
tv = ((vv != 0.0) ? Math.abs((vv - ovv)/vv) : tv);
ts = ((ss != 0.0) ? Math.abs((ss - oss)/ss) : ts);
// If decreasing, multiply the two most recent convergence measures
tvv = ((tv < otv) ? tv*otv : 1.0);
tss = ((ts < ots) ? ts*ots : 1.0);
// Compare with convergence criteria
vpass = ((tvv < betav) ? 1 : 0);
spass = ((tss < betas) ? 1 : 0);
if ((spass) || (vpass)){
// At least one sequence has passed the convergence test.
// Store variables before iterating
for (i = 0; i < N; i++) { svk[i] = K[i]; }
s = ss;
// Choose iteration according to the fastest converging sequence
stry = vtry = 0;
for ( ; ; ) {
if ((fflag && ((fflag = 0) == 0)) && ((spass) && (!vpass || (tss < tvv)))){
;// Do nothing. Provides a quick "short circuit".
}
else {
QuadIT_ak1(DBL_EPSILON, N, iPar, ui, vi, qp, NN, sdPar, p, qk, calcPar, K);
a = sdPar.a;
b = sdPar.b;
if ((iPar.NZ) > 0) return;
// Quadratic iteration has failed. Flag that it has been tried and decrease the
// convergence criterion
iFlag = vtry = 1;
betav *= 0.25;
// Try linear iteration if it has not been tried and the s sequence is converging
if (stry || (!spass)){