-
Notifications
You must be signed in to change notification settings - Fork 1
/
plots.js
2619 lines (2408 loc) · 111 KB
/
plots.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
// this script file is loaded both by the main script, and
// by subworkers. for subworkers, infnum.js needs to be
// loaded explicitly here
if (typeof importScripts === 'function') {
let scriptAppVersion = null;
if (!appVersion) {
scriptAppVersion = (function() {
let urlParams = new URLSearchParams(self.location.search);
return urlParams.has("v") ? urlParams.get('v') : "unk";
})();
}
importScripts("infnum.js?v=" + (appVersion || scriptAppVersion));
importScripts("floatexp.js?v=" + (appVersion || scriptAppVersion));
}
// use, for example, "bla-floatexp-blaepsilon1.0eminus54" for the default 1e-54 epsilon
function getBLAEpsilonFromAlgorithm(algorithm) {
if (!algorithm.includes("blaepsilon")) {
return null;
}
if (algorithm.includes("blaepsilonauto")) {
return null;
}
try {
return createInfNumFromExpStr(algorithm.split("-").find(e => e.startsWith("blaepsilon")).substring(10).replaceAll("minus","-"));
} catch (e) {
console.log("ERROR CAUGHT when parsing custom blaepsilon from algorithm name [" + algorithm + "]:");
console.log(e.name + ": " + e.message + ":\n" + e.stack.split('\n').slice(0, 5).join("\n"));
return null;
}
}
// does linear search after first checking the worst/smallest
// (last) element in the array
function searchForBestBLA(sortedArray, deltaZAbs, math) {
let hi = sortedArray.length - 1;
// we want the lowest-indexed (closest to start of array)
// BLA found to be valid
let lowestValid = null;
//let validityTestsPerformed = 0;
// special case for arrays larger than 1 BLA: test the smallest
// first, because many times the smallest (least iterations
// skipped) is not valid, in which case we don't need to test
// the rest of the BLAs in the array
if (hi > 0) {
//++validityTestsPerformed;
if (math.lt(deltaZAbs, sortedArray[hi].r2)) {
lowestValid = hi;
hi--;
} else {
return {
//validityTestsPerformed: validityTestsPerformed,
bestValidBLA: false
};
}
}
for (let x = 0; x <= hi; x++) {
//++validityTestsPerformed;
if (math.lt(deltaZAbs, sortedArray[x].r2)) {
lowestValid = x;
break;
}
}
return {
//validityTestsPerformed: validityTestsPerformed,
bestValidBLA: lowestValid === null ? false : sortedArray[lowestValid]
};
}
const windowCalcBackgroundColor = -1;
const windowCalcIgnorePointColor = -2;
// each "plot" has its own "privContext" that can contain whatever data/functions
// it needs to compute points
const plots = [{
"name": "Mandelbrot-set",
"pageTitle": "Mandelbrot set",
"calcFrom": "window",
"desc": "The Mandelbrot set is the set of complex numbers, that when repeatedly plugged into the following " +
"simple function, does <i>not</i> run away to infinity. The function is z<sub>n+1</sub> = z<sub>n</sub><sup>2</sup> + c.<br/>" +
"For each plotted point <code>c</code>, we repeat the above function many times.<br/>" +
"If the value jumps off toward infinity after say 10 iterations, we display a color at the pixel for point <code>c</code>.<br/>" +
"If the value doesn't go off toward infinity until say 50 iterations, we pick a quite different color for that point.<br/>" +
"If, after our alloted number of iterations has been computed, the value still hasn't gone off to infinity, we color that pixel the backgrond color (defaulting to black)." +
"<br/><br/>Wikipedia has a terrific <a target='_blank' href='https://en.wikipedia.org/wiki/Mandelbrot_set'>article with pictures</a>." +
"<br/><br/>My favorite explanation I've found so far is <a target='_blank' href='https://www.youtube.com/watch?v=FFftmWSzgmk'>this Numberphile video on YouTube</a>." +
"<br/><br/><b>Tips for using this Mandelbrot set viewer</b>:" +
"<br/>- When not zoomed in very far, keep the <code>n</code> (iterations) parameter low for faster calculation (use N and M keys to decrease/increase the <code>n</code> value)." +
"<br/>- To see more detail when zoomed in, increase the <code>n</code> (iterations) parameter with the M key. Calculations will be slower." +
"<br/>- <a target='_blank' href='https://philthompson.me/very-plotter-tips.html'>More tips</a>",
"gradientType": "mod",
// x and y must be infNum objects of a coordinate in the abstract plane being computed upon
"computeBoundPointColor": function(n, precis, algorithm, x, y, useSmooth) {
const maxIter = n;
// for absolute fastest speed, we'll keep a separate version of the
// regular floating point basic algorithm
if (algorithm.includes("basic") && algorithm.includes("float") && !algorithm.includes("floatexp")) {
// a squared bailout of 16 or 32 looks ok for smooth coloring, but
// when slope coloring is then applied, banding occurs. using
// even larger squared bailout (64? 128? higher?) seems to
// reduce banding artifacts for smooth+slope coloring
const bailoutSquared = useSmooth ? (32*32) : 4;
// truncating to 15 decimal digits here is equivalent to truncating
// to 16 significant digits, but it's more efficient to do both at once
//let xFloat = typeof x == "number" ? x : parseFloat(infNumExpStringTruncToLen(x, 18));
//let yFloat = typeof y == "number" ? y : parseFloat(infNumExpStringTruncToLen(y, 18));
let ix = 0;
let iy = 0;
let ixSq = 0;
let iySq = 0;
let ixTemp = 0;
let iter = 0;
while (iter < maxIter) {
ixSq = ix * ix;
iySq = iy * iy;
if (ixSq + iySq > bailoutSquared) {
break;
}
ixTemp = x + (ixSq - iySq);
iy = y + (2 * ix * iy);
ix = ixTemp;
iter++;
}
if (iter >= maxIter) {
return windowCalcBackgroundColor;
} else {
// smooth coloring (adding fractional component to integer iteration count)
// based on pseudocode on wikipedia:
// https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set#Continuous_(smooth)_coloring
if (useSmooth) {
let fracIter = Math.log(ixSq + iySq) / 2;
fracIter = Math.log(fracIter / Math.LN2) / Math.LN2;
iter += 1 - fracIter;
}
//console.log("point (" + infNumToString(x) + ", " + infNumToString(y) + ") exploded on the [" + iter + "]th iteration");
return iter;
}
}
const math = selectMathInterfaceFromAlgorithm(algorithm);
const bailoutSquared = useSmooth ? math.createFromNumber(32*32) : math.four;
// the coords used for iteration
const xConv = typeof x.v == "bigint" ? math.createFromInfNum(x) : math.createFromExpString(floatExpToString(x));
const yConv = typeof y.v == "bigint" ? math.createFromInfNum(y) : math.createFromExpString(floatExpToString(y));
var ix = structuredClone(math.zero);
var iy = structuredClone(math.zero);
var ixSq = structuredClone(math.zero);
var iySq = structuredClone(math.zero);
var ixTemp = structuredClone(math.zero);
var iter = 0;
try {
while (iter < maxIter) {
ixSq = math.mul(ix, ix);
iySq = math.mul(iy, iy);
if (math.gt(math.add(ixSq, iySq), bailoutSquared)) {
break;
}
ixTemp = math.add(xConv, math.sub(ixSq, iySq));
iy = math.add(yConv, math.mul(math.two, math.mul(ix, iy)));
ix = ixTemp;
ix = math.truncateToSigDig(ix, precis);
iy = math.truncateToSigDig(iy, precis);
iter++;
}
if (iter == maxIter) {
return windowCalcBackgroundColor;
} else {
// smooth coloring (adding fractional component to integer iteration count)
// based on pseudocode on wikipedia:
// https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set#Continuous_(smooth)_coloring
if (useSmooth) {
// math.log() returns a float
let fracIter = math.log(math.add(ixSq, iySq)) / 2;
fracIter = Math.log(fracIter / Math.LN2) / Math.LN2;
iter += 1 - fracIter;
}
//console.log("point (" + infNumToString(x) + ", " + infNumToString(y) + ") exploded on the [" + iter + "]th iteration");
return iter;
}
} catch (e) {
console.log("ERROR CAUGHT when processing point (x, y, iter, maxIter): [" + math.toExpString(x) + ", " + math.toExpString(y) + ", " + iter + ", " + maxIter + "]:");
console.log(e.name + ": " + e.message + ":\n" + e.stack.split('\n').slice(0, 5).join("\n"));
return windowCalcIgnorePointColor; // special color value that will not be displayed
}
},
// x and y must be infNum objects of a coordinate in the abstract plane being computed upon
"computeBoundPointColorStripes": function(n, precis, algorithm, x, y, useSmooth) {
// odd stripeDensity values create the weird swooping artifacts!
let stripeDensity = 6.0; // anywhere from -10 to +10?
// for stripe average we need to skip the first (0th) iteration
const stripeSkipFirstIters = 0;
const maxIter = n;
// this scales up the final result, increasing the number of
// colors. a mixFactor of 1000 works ok, but in some areas
// there are rather abrupt color boundaries where a smooth
// gradient is expected.
const mixFactor = 100000;
// use user-provided coloring params
let userStripeDensity;
try {
userStripeDensity = parseFloat(algorithm.split("-").find(e => e.startsWith("stripedensity")).substring(13));
} catch (e) {}
if (userStripeDensity !== undefined && userStripeDensity >= 0.1 && userStripeDensity <= 100.0) {
stripeDensity = userStripeDensity;
}
// TODO: consider allowing bailout (integer) to be specified by user in algorithm string
const bailoutSquared = useSmooth ? (64*64) : 4;
const logBailoutSquared = Math.log(bailoutSquared);
// truncating to 15 decimal digits here is equivalent to truncating
// to 16 significant digits, but it's more efficient to do both at once
//let xFloat = typeof x == "number" ? x : parseFloat(infNumExpStringTruncToLen(x, 18));
//let yFloat = typeof y == "number" ? y : parseFloat(infNumExpStringTruncToLen(y, 18));
let ix = 0;
let iy = 0;
let ixSq = 0;
let iySq = 0;
let ixTemp = 0;
let iter = 0;
let avgCount = 0;
let avg = 0;
let lastAdded = 0;
let lastZ2 = 0; // last squared length
//let triPrevZ2 = 0; // before last squared length, for triangle inequality average
while (iter < maxIter) {
ixSq = ix * ix;
iySq = iy * iy;
if (iter > stripeSkipFirstIters) {
// comment this out for TIA
avgCount++;
// stripe addend function
lastAdded = (0.5 * Math.sin(stripeDensity * Math.atan(iy / ix))) + 0.5;
// dbyrne addend function (https://www.fractalforums.com/programming/faster-alternative-to-tia-coloring/)
//lastAdded = Math.min(Math.abs(iy / ix), 2.0);
// "atan(value)" from "mandelbrowser" android app author:
//lastAdded = Math.abs(Math.atan(iy / ix));
//lastAdded = 1 / (1 + Math.atan(iy / ix));
//lastAdded = 1 / (1 + Math.abs(Math.atan(iy / ix)));
// "log(abs(value))" from "mandelbrowser" android app author:
//lastAdded = Math.log(Math.abs(ixSq + iySq));
//lastAdded = 1 / (1 + Math.log(Math.abs(ixSq + iySq)));
// similar to above, but sqrt
//lastAdded = 1 / (1 + Math.log(Math.sqrt(ixSq + iySq)));
// comment this out for TIA
avg += lastAdded;
}
// for testing triangle inequality average
//triPrevZ2 = lastZ2;
lastZ2 = ixSq + iySq;
if (lastZ2 > bailoutSquared /*&& iter > stripeSkipFirstIters*/) {
break;
}
// trying triangle here, since the |z| is not escaped
//let zOldMag = Math.sqrt(triPrevZ2);
//let cMag = Math.sqrt(x*x + y*y); // this can be calculated once, outside the loop
//let triMin = Math.abs(zOldMag - cMag);
//let triMax = zOldMag + cMag;
//let fracNum = Math.sqrt(lastZ2) - triMin;
//let fracDen = triMax - triMin;
//if (fracDen != 0) {
// avgCount++;
// lastAdded = fracNum / fracDen;
// avg += lastAdded;
//}
ixTemp = x + (ixSq - iySq);
iy = y + (2 * ix * iy);
ix = ixTemp;
iter++;
}
if (iter >= maxIter) {
return windowCalcBackgroundColor;
} else {
if (!useSmooth) {
return avg / avgCount;
}
let prevAvg = (avg - lastAdded) / (avgCount - 1);
avg = avg / avgCount;
let frac = 1.0 + Math.log2(logBailoutSquared/Math.log(lastZ2));
let mix = frac * avg + ((1.0 - frac) * prevAvg);
return mix * mixFactor;
}
},
"computeBoundPointColorCurvature": function(n, precis, algorithm, x, y, useSmooth) {
// for curvature average, we must skip the first 2 iterations
// to avoid divide-by-zero -- for stripe average we need
// to skip the first (0th)
const skipFirstIters = 1;
const maxIter = n;
// this scales up the final result, increasing the number of
// colors. a mixFactor of 1000 works ok, but in some areas
// there are rather abrupt color boundaries where a smooth
// gradient is expected.
const mixFactor = 100000;
// TODO: consider allowing bailout (integer) to be specified by user in algorithm string
const bailoutSquared = useSmooth ? (64*64) : 4;
const logBailoutSquared = Math.log(bailoutSquared);
// truncating to 15 decimal digits here is equivalent to truncating
// to 16 significant digits, but it's more efficient to do both at once
//let xFloat = typeof x == "number" ? x : parseFloat(infNumExpStringTruncToLen(x, 18));
//let yFloat = typeof y == "number" ? y : parseFloat(infNumExpStringTruncToLen(y, 18));
let ix = 0;
let iy = 0;
let ixSq = 0;
let iySq = 0;
let ixTemp = 0;
let iter = 0;
let avgCount = 0;
let avg = 0;
let lastAdded = 0;
let lastZ2 = 0; // last squared length
let currentZ = {x: 0, y: 0};
let oneZ = {x: 0, y: 0}; // z (coord. at iteration) one iteration ago
let twoZ = {x: 0, y: 0}; // z (coord. at iteration) two iterations ago
while (iter < maxIter) {
ixSq = ix * ix;
iySq = iy * iy;
lastZ2 = ixSq + iySq;
// curvature average (https://en.wikibooks.org/wiki/Fractals%2FIterations_in_the_complex_plane%2Ftriangle_ineq#CAA)
twoZ = oneZ;
oneZ = currentZ;
currentZ = {x: ix, y: iy};
if (iter > skipFirstIters) {
let curveNum = {x: currentZ.x - oneZ.x, y: currentZ.y - oneZ.y};
let curveDen = {x: oneZ.x - twoZ.x, y: oneZ.y - twoZ.y};
let curveQuot = floatMath.complexDiv(curveNum, curveDen);
if (curveQuot.x != 0) {
avgCount++;
// the 1.2 here may be a parameter that could be exposed to the user
// in the algorithm string, similar to -stripedensity# used with
// stripe average coloring
lastAdded = Math.abs(1.2 * Math.atan(curveQuot.y / curveQuot.x));
avg += lastAdded;
}
}
if (lastZ2 > bailoutSquared /*&& iter > skipFirstIters*/) {
break;
}
ixTemp = x + (ixSq - iySq);
iy = y + (2 * ix * iy);
ix = ixTemp;
iter++;
}
if (iter >= maxIter) {
return windowCalcBackgroundColor;
} else {
if (!useSmooth) {
return avg / avgCount;
}
let prevAvg = (avg - lastAdded) / (avgCount - 1);
avg = avg / avgCount;
let frac = 1.0 + Math.log2(logBailoutSquared/Math.log(lastZ2));
let mix = frac * avg + ((1.0 - frac) * prevAvg);
return mix * mixFactor;
}
},
// x and y must be infNum objects of a coordinate in the abstract plane being computed upon
"computeReferenceOrbit": function(n, precis, algorithm, x, y, period, useSmooth, fnContext) {
const outputMath = selectMathInterfaceFromAlgorithm(algorithm);
const outputIsFloatExp = outputMath.name == "floatexp";
const useStripes = algorithm.includes("stripes");
const periodLessThanN = period !== null && period > 0 && period < n;
// add two exta iterations to periodic orbits for debugging below
const maxIter = periodLessThanN ? (period+2) : n;
const two = infNum(2n, 0n);
const four = infNum(4n, 0n);
const sixteen = infNum(16n, 0n);
// try using slightly larger bailout (4) for ref orbit
// than for perturb orbit (which uses smallest possible
// bailout of 2)
// for smooth coloring, our bailout is much larger (32*32)
// so our ref orbit bailout must be larger than than (32*32*2)
// for stripes coloring, out bailout must be even larger (64*64)
// with larger ref orbit bailout
const bailoutSquared = useStripes ?
(useSmooth ? infNum(64n*64n*2n, 0n) : sixteen)
:
(useSmooth ? infNum(32n*32n*2n, 0n) : sixteen);
// fnContext allows the loop to be done piecemeal
if (fnContext === null) {
fnContext = {
// the coords used for iteration
ix: infNum(0n, 0n),
iy: infNum(0n, 0n),
iter: 0,
orbit: [],
status: "",
done: false
};
}
var ixSq = infNum(0n, 0n);
var iySq = infNum(0n, 0n);
var ixTemp = infNum(0n, 0n);
var statusIterCounter = 0;
try {
while (fnContext.iter < maxIter) {
ixSq = infNumMul(fnContext.ix, fnContext.ix);
iySq = infNumMul(fnContext.iy, fnContext.iy);
if (infNumGt(infNumAdd(ixSq, iySq), bailoutSquared)) {
break;
}
fnContext.orbit.push({
x: outputMath.createFromInfNum(fnContext.ix),
y: outputMath.createFromInfNum(fnContext.iy),
// if needed, include floatexp x and y as well, for SA coefficients calc
// (if outputMath is floatexp, x and y are already floatexp, then we
// don't need another floatexp version of those here)
xfxp: outputIsFloatExp ? null : floatExpMath.createFromInfNum(fnContext.ix),
yfxp: outputIsFloatExp ? null : floatExpMath.createFromInfNum(fnContext.iy)
});
ixTemp = infNumAdd(x, infNumSub(ixSq, iySq));
fnContext.iy = infNumAdd(y, infNumMul(two, infNumMul(fnContext.ix, fnContext.iy)));
fnContext.ix = copyInfNum(ixTemp);
fnContext.ix = infNumTruncateToLen(fnContext.ix, precis);
fnContext.iy = infNumTruncateToLen(fnContext.iy, precis);
fnContext.iter++;
statusIterCounter++;
if (statusIterCounter >= 5000) {
statusIterCounter = 0;
fnContext.status = "computed " + (Math.round(fnContext.iter * 10000.0 / maxIter)/100.0) + "% of reference orbit";
console.log(fnContext.status);
return fnContext;
}
}
// debug... to see if we actually have a periodic orbit here
if (periodLessThanN) {
// remove the two extra iterations we computed
const periodPlusTwoIter = fnContext.orbit.pop(); // (period+2)th iteration should be equal to the 2nd (index 1) iter
const periodPlusOneIter = fnContext.orbit.pop(); // (period+1)th iteration should be zero
const firstIter = fnContext.orbit[0];
const secondIter = fnContext.orbit[1];
console.log("the full period of [" + period + "] iters has been computed, " +
"where the orbit has [" + fnContext.orbit.length + "] iters, where the first orbit iter is (should be zero):\n",
{x:outputMath.toExpString(firstIter.x), y:outputMath.toExpString(firstIter.y)},
" and where the last orbit iter is:\n",
{x:outputMath.toExpString(fnContext.orbit[fnContext.orbit.length-1].x), y:outputMath.toExpString(fnContext.orbit[fnContext.orbit.length-1].y)},
" and where the next [" + (period+1) + "]th iteration (should be (~0, ~0)) would be at:\n",
{x:outputMath.toExpString(periodPlusOneIter.x), y:outputMath.toExpString(periodPlusOneIter.y)},
" and where the next [" + (period+2) + "]th iteration would be at:\n",
{x:outputMath.toExpString(periodPlusTwoIter.x), y:outputMath.toExpString(periodPlusTwoIter.y)},
" which should be equal to, or close to, the 1th (2nd) iter:\n",
{x:outputMath.toExpString(secondIter.x), y:outputMath.toExpString(secondIter.y)});
}
// fill out reference orbit with repeat data
// - this greatly slows down BLA and shouldn't be done with BLA
// - with non-BLA (perturb, or perturb+SA) this doesn't need to be
// done because, currently, the period isn't found and thus the
// ref orbit isn't shortened to just the period for those algos
//if (periodLessThanN && fnContext.iter >= maxIter) {
// for (let i = 0; i < n - period; i++) {
// // use mod to keep looping back over the ref orbit iterations
// fnContext.orbit.push(structuredClone(fnContext.orbit[i % period]));
// }
//}
fnContext.done = true;
return fnContext;
} catch (e) {
console.log("ERROR CAUGHT when computing reference orbit at point (x, y, iter, maxIter): [" + infNumToString(x) + ", " + infNumToString(y) + ", " + fnContext.iter + ", " + maxIter + "]:");
console.log(e.name + ": " + e.message + ":\n" + e.stack.split('\n').slice(0, 5).join("\n"));
fnContext.done = true;
return fnContext;
}
},
// remove starting here for minify
// based on garrit's matlab code: https://fractalforums.org/index.php?topic=3805.msg24312#msg24312
// this function isn't used in v0.10.0, instead, a version of this function
// that itself calls the newton's method function is used
"findPeriodBallArithmetic1stOrder": function(n, precis, algorithm, x, y, width, height, doCont) {
// in ball centered on (x+yi) find period (up to n) of nucleus
// doCont = false normally
//
// i believe:
// x = center coordinate of screen
// y = center coordinate of screen
// width = half screen width (half rendered window width, in plane units, not in pixels)
// height = half screen height (half rendered window height, in plane units, not in pixels)
//const math = selectMathInterfaceFromAlgorithm(algorithm);
// infnum is likely more accurate at very large scales, but is much
// slower than float and floatexp... but infnum if the only way
// to do full-precision computations
const math = infNumMath;
const c0 = {
x: math.createFromInfNum(x),
y: math.createFromInfNum(y)
};
const r0 = math.min(math.createFromInfNum(width), math.createFromInfNum(height));
let z = math.complexRealMul(c0, math.zero);
let r = r0;
//let p = []; // this doesn't appear to be used
const maxR = math.createFromNumber(1e5);
let az = math.complexAbs(z);
for (let k = 1; k < n; k++) {
// r = (az+r).^mpow - az.^mpow + r0;
r = math.add(az, r);
r = math.mul(r, r);
r = math.sub(r, math.mul(az, az));
r = math.add(r, r0);
// z = z.^mpow + c0;
z = math.complexAdd(math.complexMul(z, z), c0);
az = math.complexAbs(z);
// what all needs to be truncated?
z.x = math.truncateToSigDig(z.x, precis);
z.y = math.truncateToSigDig(z.y, precis);
r = infNumTruncateToLen(r, precis);
az = infNumTruncateToLen(az, precis);
if (math.gt(r, az)) {
//p = [p k];
console.log("period found with 1st-order ball arithmetic:", k);
if (!doCont) {
break;
}
}
if (math.gt(az, maxR) || math.gt(r, maxR)) {
console.log("1st-order ball arithmetic escaped at iteration:", k);
break;
}
}
},
// remove ending here for minify
// based on garrit's matlab code: https://fractalforums.org/index.php?topic=3805.msg24312#msg24312
// this is the function used in v0.10.0 because it can resume looking for deeper, higher-period
// minibrots if a found nucleus is off-screen. it can resume because it itself calls the
// "getNthIterationAndDerivative()" and "newtonsMethod()" functions, which are passed as
// parameters
"findMinibrotWithBallArithmetic1stOrderAndNewton": function(n, precis, algorithm, x, y, viewWidth, viewHeight, getNthIterationAndDerivative, newtonsMethod, fnContext) {
// in ball centered on (x+yi) find period (up to n) of nucleus
// doCont = false normally
//
// i believe:
// x = center coordinate of screen
// y = center coordinate of screen
// width = half screen width (half rendered window width, in plane units, not in pixels)
// height = half screen height (half rendered window height, in plane units, not in pixels)
//const math = selectMathInterfaceFromAlgorithm(algorithm);
// infnum is likely more accurate at very large scales, but is much
// slower than float and floatexp... but infnum if the only way
// to do full-precision computations
const math = infNumMath;
let z;
let r;
const maxR = math.createFromNumber(1e5);
// fnContext allows the loop to be done piecemeal
if (fnContext === null) {
const r0init = math.min(math.createFromInfNum(viewWidth), math.createFromInfNum(viewHeight));
const c0init = {
x: math.createFromInfNum(x),
y: math.createFromInfNum(y)
};
fnContext = {
c0: c0init,
r0: r0init,
r0sq: math.mul(r0init, r0init),
//z: not a constant -- set below,
//r: not a constant -- set below,
az: math.zero,
k: 1, // starting at 1, not 0
newtonFnStatus: null,
nucleus: null,
status: "",
done: false
};
z = math.complexRealMul(c0init, math.zero);
r = r0init;
} else {
z = fnContext.z;
r = fnContext.r;
}
let az = fnContext.az;
const c0 = fnContext.c0;
const r0 = fnContext.r0;
const r0sq = fnContext.r0sq;
while (fnContext.k < n) {
if (fnContext.newtonFnStatus === null) {
// r = (az+r).^mpow - az.^mpow + r0;
r = math.add(az, r);
r = math.mul(r, r);
r = math.sub(r, math.mul(az, az));
r = math.add(r, r0);
// z = z.^mpow + c0;
z = math.complexAdd(math.complexMul(z, z), c0);
az = math.complexAbs(z);
// what all needs to be truncated?
z.x = infNumTruncateToLen(z.x, precis);
z.y = infNumTruncateToLen(z.y, precis);
r = infNumTruncateToLen(r, precis);
az = infNumTruncateToLen(az, precis);
}
if (math.gt(r, az)) {
if (fnContext.newtonFnStatus === null) {
fnContext.z = z;
fnContext.r = r;
fnContext.az = az;
console.log("period found with 1st-order ball arithmetic:", fnContext.k);
}
// use newton's method to find minibrot nucleus
if (fnContext.newtonFnStatus === null || !fnContext.newtonFnStatus.done) {
fnContext.newtonFnStatus = newtonsMethod(fnContext.k, x, y, precis, getNthIterationAndDerivative, fnContext.newtonFnStatus);
if (!fnContext.newtonFnStatus.done) {
fnContext.status = fnContext.newtonFnStatus.status;
return fnContext;
}
}
fnContext.nucleus = fnContext.newtonFnStatus.c;
fnContext.newtonFnStatus = null;
// if the nucleus is within the original radius, we're done!
if (math.lt(math.complexAbsSquared(math.complexSub(fnContext.nucleus, c0)), r0sq)) {
console.log("found on-screen ref x/y/period!");
fnContext.nucleus.period = fnContext.k;
fnContext.done = true;
return fnContext;
// otherwise, proceed to try to find a deeper higher-period
} else {
console.log("newton nucleus with period [" + fnContext.k + "] is off screen!");
fnContext.nucleus = null;
}
}
if (math.gt(az, maxR) || math.gt(r, maxR)) {
console.log("1st-order ball arithmetic escaped at iteration:", fnContext.k);
fnContext.nucleus = null;
fnContext.done = true;
return fnContext;
}
fnContext.k++;
if (fnContext.k % 5000 === 0) {
fnContext.z = z;
fnContext.r = r;
fnContext.az = az;
fnContext.status = "1st-order ball arithmetic at iter. [" + fnContext.k.toLocaleString() + "]";
console.log("1st-order ball arithmetic at iteration:", fnContext.k);
return fnContext;
}
}
fnContext.nucleus = null;
fnContext.done = true;
return fnContext;
},
// remove starting here for minify
// based on garrit's matlab code: https://fractalforums.org/index.php?topic=3805.msg24312#msg24312
// this function was never used: the 1st order version is much much faster
"findPeriodBallArithmetic2ndOrder": function(n, precis, algorithm, x, y, width, height, doCont) {
// in ball centered on (x+yi) find period (up to n) of nucleus
// doCont = false normally
//
// i believe:
// x = center coordinate of screen
// y = center coordinate of screen
// width = half screen width (half rendered window width, in plane units, not in pixels)
// height = half screen height (half rendered window height, in plane units, not in pixels)
//const math = selectMathInterfaceFromAlgorithm(algorithm);
// infnum is likely more accurate at very large scales, but is much
// slower than float and floatexp... but infnum if the only way
// to do full-precision computations
const math = infNumMath;
//const math = floatExpMath;
const c0 = {
x: math.createFromInfNum(x),
y: math.createFromInfNum(y)
};
const r0 = math.min(math.createFromInfNum(width), math.createFromInfNum(height));
const r0sq = math.mul(r0, r0);
let z = math.complexRealMul(c0, math.zero);
//let c1 = c0;
let dz = math.complexRealMul(c0, math.zero);
let r = r0;
//let p = []; // this doesn't appear to be used
const maxR = math.createFromNumber(1e5);
let az = math.complexAbs(z);
let adz = math.complexAbs(dz);
let minz = math.createFromNumber(1e16);
let minIter = -1;
let rsq;
let r0sqadzsq;
const nthIterToLog = 100;
let nthIterToLogCount = 0;
for (let k = 1; k < n; k++) {
nthIterToLogCount++;
if (nthIterToLogCount >= nthIterToLog) {
nthIterToLogCount = 0;
console.log("2nd-order ball arithmetic at iteration:", k);
}
// r = r.^2+2*(az+r0.*adz)*r + r0.^2.*adz.^2;
rsq = math.mul(r, r);
r = math.mul(r, math.mul(math.two, math.add(az, math.mul(r0, adz))));
r0sqadzsq = math.mul(r0sq, math.mul(adz, adz));
r = math.add(rsq, math.add(r, r0sqadzsq));
// dz = 2*z.*dz + 1;
dz = math.complexRealMul(math.complexMul(z, dz), math.two);
dz = math.complexRealAdd(dz, math.one);
// z = z.^2 + c0;
z = math.complexAdd(math.complexMul(z, z), c0);
az = math.complexAbs(z);
adz = math.complexAbs(dz);
// what all needs to be truncated?
z.x = math.truncateToSigDig(z.x, precis);
z.y = math.truncateToSigDig(z.y, precis);
r = math.truncateToSigDig(r, precis);
az = math.truncateToSigDig(az, precis);
adz = math.truncateToSigDig(adz, precis);
if (math.lt(az, minz)) {
minz = az;
minIter = k;
}
if (math.gt(math.add(r, math.mul(r0, adz)), az)) {
//p = [p k];
console.log("period found with 2nd-order ball arithmetic:", k, "atom:", minIter);
if (!doCont) {
//break;
return k;
}
}
if (math.gt(az, maxR) || math.gt(r, maxR)) {
console.log("2nd-order ball arithmetic escaped at iteration:", k);
//break;
return -1;
}
}
return -1;
},
// remove ending here for minify
// remove starting here for minify
// this function was never used: the 1st order version is much much faster
"findMinibrotWithBallArithmetic2ndOrderAndNewton": function(n, precis, algorithm, x, y, viewWidth, viewHeight, getNthIterationAndDerivative, newtonsMethod) {
// in ball centered on (x+yi) find period (up to n) of nucleus
// doCont = false normally
//
// i believe:
// x = center coordinate of screen
// y = center coordinate of screen
// viewWidth = half screen width in the x/real dimension (half rendered window width, in plane units, not in pixels)
// viewHeight = half screen height in the y/imag dimension (half rendered window height, in plane units, not in pixels)
//const math = selectMathInterfaceFromAlgorithm(algorithm);
// infnum is likely more accurate at very large scales, but is much
// slower than float and floatexp... but infnum if the only way
// to do full-precision computations
const math = infNumMath;
//const math = floatExpMath;
const c0 = {
x: math.createFromInfNum(x),
y: math.createFromInfNum(y)
};
const r0 = math.min(math.createFromInfNum(viewWidth), math.createFromInfNum(viewHeight));
const r0sq = math.mul(r0, r0);
let z = math.complexRealMul(c0, math.zero);
//let c1 = c0;
let dz = math.complexRealMul(c0, math.zero);
let r = r0;
//let p = []; // this doesn't appear to be used
const maxR = math.createFromNumber(1e5);
let az = math.complexAbs(z);
let adz = math.complexAbs(dz);
let minz = math.createFromNumber(1e16);
let minIter = -1;
let rsq;
let r0sqadzsq;
const nthIterToLog = 20;
let nthIterToLogCount = 0;
for (let k = 1; k < n; k++) {
nthIterToLogCount++;
if (nthIterToLogCount >= nthIterToLog) {
nthIterToLogCount = 0;
console.log("2nd-order ball arithmetic at iteration:", k);
}
// r = r.^2+2*(az+r0.*adz)*r + r0.^2.*adz.^2;
rsq = math.mul(r, r);
r = math.mul(r, math.mul(math.two, math.add(az, math.mul(r0, adz))));
r0sqadzsq = math.mul(r0sq, math.mul(adz, adz));
r = math.add(rsq, math.add(r, r0sqadzsq));
// dz = 2*z.*dz + 1;
dz = math.complexRealMul(math.complexMul(z, dz), math.two);
dz = math.complexRealAdd(dz, math.one);
// z = z.^2 + c0;
z = math.complexAdd(math.complexMul(z, z), c0);
az = math.complexAbs(z);
adz = math.complexAbs(dz);
// what all needs to be truncated?
z.x = math.truncateToSigDig(z.x, precis);
z.y = math.truncateToSigDig(z.y, precis);
r = math.truncateToSigDig(r, precis);
az = math.truncateToSigDig(az, precis);
adz = math.truncateToSigDig(adz, precis);
if (math.lt(az, minz)) {
minz = az;
minIter = k;
}
if (math.gt(math.add(r, math.mul(r0, adz)), az)) {
//p = [p k];
console.log("period found with 2nd-order ball arithmetic:", k, "atom:", minIter);
// use newton's method to find minibrot nucleus
const foundMinibrotNucleus = newtonsMethod(k, x, y, precis, getNthIterationAndDerivative);
// if the nucleus is within the original radius, we're done!
if (math.lt(math.complexAbsSquared(math.complexSub(foundMinibrotNucleus, c0)), r0sq)) {
console.log("found on-screen ref x/y/period!");
foundMinibrotNucleus.period = k;
return foundMinibrotNucleus;
// otherwise, proceed to try to find a deeper higher-period
} else {
console.log("newton nucleus with period [" + k + "] is off screen!");
}
}
if (math.gt(az, maxR) || math.gt(r, maxR)) {
console.log("2nd-order ball arithmetic escaped at iteration:", k);
//break;
//return -1;
return null;
}
}
//return -1;
return null;
},
// remove ending here for minify
// this is largely the same as "computeReferenceOrbit" above, but also
// performs iterations of the derivative mandelbrot function
// x and y must be infNum objects
// for newton's method for finding minibrots/periodic ref orbit locations: https://www.fractalforums.com/index.php?topic=18289.msg90972#msg90972
"getNthIterationAndDerivative": function(n, x, y, precis, fnContext) {
// we are just using a large bailout here, as large
// or larger than any algorithm would use
const bailoutSquared = infNum(64n*64n*2n, 0n);
// fnContext allows the loop to be done piecemeal
if (fnContext === null) {
fnContext = {
// the coords used for iteration
//ix: infNum(0n, 0n),
//iy: infNum(0n, 0n),
z: {x:infNum(0n, 0n), y:infNum(0n, 0n)}, // the nth iteration of the mandelbrot equation
//z1: {x:infNum(0n, 0n), y:infNum(0n, 0n)}, // the 1th iteration of the mandelbrot equation
//znplus1: {x:infNum(0n, 0n), y:infNum(0n, 0n)}, // the n+1th iteration of the mandelbrot equation
//zsave: {x:infNum(0n, 0n), y:infNum(0n, 0n)}, // save the nth iteration of the mandelbrot equation
dz: {x:infNum(0n, 0n), y:infNum(0n, 0n)}, // the nth iteration of the derivative of the mandelbrot equation
c: {x: copyInfNum(x), y: copyInfNum(y)},
iter: 0,
status: "",
done: false
};
}
var ixSq = infNum(0n, 0n);
var iySq = infNum(0n, 0n);
var ixTemp = infNum(0n, 0n);
var statusIterCounter = 0;
try {
//while (fnContext.iter < n+2) {
while (fnContext.iter < n) {
// dz = 2 * z * dz + 1
fnContext.dz = infNumMath.complexRealAdd(
infNumMath.complexRealMul(
infNumMath.complexMul(
fnContext.z,
fnContext.dz),
infNumMath.two),
infNumMath.one);
// z = z * z + c
//fnContext.z = infNumMath.complexAdd(
// infNumMath.complexMul(fnContext.z, fnContext.z),
// fnContext.c
// );
ixSq = infNumMul(fnContext.z.x, fnContext.z.x);
iySq = infNumMul(fnContext.z.y, fnContext.z.y);
if (infNumGt(infNumAdd(ixSq, iySq), bailoutSquared)) {
break;
}
//fnContext.z.x = infNumTruncateToLen(fnContext.z.x, precis);
//fnContext.z.y = infNumTruncateToLen(fnContext.z.y, precis);
fnContext.dz.x = infNumTruncateToLen(fnContext.dz.x, precis);
fnContext.dz.y = infNumTruncateToLen(fnContext.dz.y, precis);
ixTemp = infNumAdd(x, infNumSub(ixSq, iySq));
fnContext.z.y = infNumAdd(y, infNumMul(infNumMath.two, infNumMul(fnContext.z.x, fnContext.z.y)));
fnContext.z.x = copyInfNum(ixTemp);
fnContext.z.x = infNumTruncateToLen(fnContext.z.x, precis);
fnContext.z.y = infNumTruncateToLen(fnContext.z.y, precis);
//if (fnContext.iter === 1) {
// fnContext.z1 = structuredClone(fnContext.z); // use index 1th iter for period detection
//} else if (fnContext.iter === n-1) {
// fnContext.zsave = structuredClone(fnContext.z); // save the nth iter
//} else if (fnContext.iter === n+1) {
// fnContext.znplus1 = structuredClone(fnContext.z); // use n+1th iter for period detection
//}
fnContext.iter++;
statusIterCounter++;
if (statusIterCounter >= 10000) {
statusIterCounter = 0;
fnContext.status = "at " + (Math.round(fnContext.iter * 10000.0 / n)/100.0) + "% of orbit";
console.log(fnContext.status);
return fnContext;
}
}
//fnContext.z = structuredClone(fnContext.zsave);
fnContext.status = "at " + (Math.round(fnContext.iter * 10000.0 / n)/100.0) + "% of orbit";
fnContext.done = true;
return fnContext;
} catch (e) {
console.log("ERROR CAUGHT when computing Nth iteration and derivative (x, y, iter, maxIter): [" + infNumToString(x) + ", " + infNumToString(y) + ", " + fnContext.iter + ", " + n + "]:");
console.log(e.name + ": " + e.message + ":\n" + e.stack.split('\n').slice(0, 5).join("\n"));
fnContext.done = true;
return fnContext;
}
},
// newton's method for finding minibrots/periodic ref orbit locations: https://www.fractalforums.com/index.php?topic=18289.msg90972#msg90972
"newtonsMethod": function(period, x, y, precis, getNthIterationAndDerivative, fnCtx) {
const maxSteps = 24;
// for low-ish values of precis (<400ish) we want to ensure
// we are checking at least 3 fewer digits, so use Math.min()
const closeEnoughPrecis = Math.min(precis - 3, Math.floor(precis * 0.995));
// fnCtx allows the loop to be done piecemeal
if (fnCtx === null) {
fnCtx = {
nthIterState: null,
c: {x: copyInfNum(x), y: copyInfNum(y)},
i: 0,
status: "",
done: false
};
}
let step;
let cPrev;
while (fnCtx.i < maxSteps) {
// calculate the Nth iteration of regular+deriviative
if (fnCtx.nthIterState === null || !fnCtx.nthIterState.done) {
fnCtx.nthIterState = getNthIterationAndDerivative(period, fnCtx.c.x, fnCtx.c.y, precis, fnCtx.nthIterState);
fnCtx.status = "for " + numberWithOrdinalSuffix(fnCtx.i+1) + " Newton's iteration, " + fnCtx.nthIterState.status;
return fnCtx;
}
// if dz is zero, stop
//if (nthIterationState.dz.x.v == 0n) {
// console.log("newton's method stopped during the [" + (i+1) + "]th iteration because dz was zero");
// break;
//}
// if the 1th (2nd iter) and n+1th (2nd after period) are ~equal, then we've found a periodic point
//if (
// infNumApproxEq(fnCtx.nthIterState.z1.x, fnCtx.nthIterState.znplus1.x, precis) &&
// infNumApproxEq(fnCtx.nthIterState.z1.y, fnCtx.nthIterState.znplus1.y, precis)) {
// console.log("newton's method stopped during the [" + (i+1) + "]th iteration because we found a periodic point with period [" + period + "]");