forked from philthompson/visualize-primes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinfnum.js
1333 lines (1186 loc) · 40.6 KB
/
infnum.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
// remove starting here for minify
var doUnitTests = false;
//var heronsIterations = 0;
var doPerfTests = false;
// remove ending here for minify
function replaceAllEachChar(subject, replaceThese, replaceWith) {
var s = subject;
for (let i = 0; i < replaceThese.length; i++) {
s = s.replaceAll(replaceThese.charAt(i), replaceWith);
}
return s;
}
function infNum(value, exponent) {
return {"v": value, "e": exponent};
}
function trimZeroesOld(stringNum) {
var trimmed = stringNum.trim();
const negative = trimmed.startsWith('-');
if (negative) {
trimmed = trimmed.substr(1);
}
while (trimmed.length > 1 && trimmed.startsWith('0')) {
trimmed = trimmed.substr(1);
}
if (negative) {
trimmed = "-" + trimmed;
}
const parts = trimmed.split('.');
if (parts.length == 1) {
return trimmed;
}
while (parts[1].length > 0 && parts[1].endsWith('0')) {
parts[1] = parts[1].slice(0, -1);
}
if (parts[1].length == 0) {
return trimmed;
}
return parts[0] + "." + parts[1];
}
function trimZeroes(stringNum) {
var parts = stringNum.trim().split('.');
const negative = parts[0].startsWith('-');
if (negative) {
parts[0] = parts[0].substr(1);
}
let leadingZeroes = 0;
for (let i = 0; i < parts[0].length - 1; i++) {
if (parts[0].charAt(i) === '0') {
leadingZeroes++;
} else {
break;
}
}
parts[0] = parts[0].substring(leadingZeroes);
if (parts[0].length == 0) {
parts[0] = "0";
}
if (negative) {
parts[0] = "-" + parts[0];
}
if (parts.length == 1 || parts[1].length == 0) {
return parts[0];
}
let trailingZeroes = 0;
for (let i = parts[1].length - 1; i >= 0; i--) {
if (parts[1].charAt(i) === '0') {
trailingZeroes--;
} else {
break;
}
}
if (trailingZeroes < 0) {
parts[1] = parts[1].slice(0, trailingZeroes);
if (parts[1].length == 0) {
return parts[0];
}
}
return parts[0] + "." + parts[1];
}
function createInfNum(stringNum) {
if (stringNum.includes("e") || stringNum.includes("E")) {
const split = replaceAllEachChar(stringNum, ", ", "").replaceAll("E", "e").split("e");
let value = split[0];
let exponent = 0;
if (value.includes(".")) {
let valSplit = value.split(".");
exponent -= valSplit[1].length;
value = valSplit[0] + valSplit[1];
}
exponent += parseInt(split[1]);
return infNum(BigInt(value), BigInt(exponent));
} else {
var trimmed = trimZeroes(stringNum);
const parts = trimmed.split('.');
if (parts.length == 1) {
return infNum(BigInt(parts[0]), 0n);
}
return infNum(BigInt(parts[0] + "" + parts[1]), BigInt("-" + parts[1].length));
}
}
// after a quick test this seems to actually create a copy
function copyInfNum(n) {
return infNum(n.v+0n, n.e+0n);
}
// only reads values from a and b, so the given objects are never modified
function infNumMul(a, b) {
// the product of the values
// the sum of the exponents
return infNum(a.v * b.v, a.e + b.e);
}
// adjust the exponents to make them the same, by
// increasing the value part of the InfNum with the
// larger exponent
function normInfNum(argA, argB) {
var a = copyInfNum(argA);
var b = copyInfNum(argB);
// if they already have the same exponent, our work is done
if (a.e === b.e) {
return [a, b];
}
var swapped = false;
// find which operand has smaller exponent
var s = a;
var l = b;
if (l.e < s.e) {
swapped = true;
s = b;
l = a;
}
const expDiff = l.e - s.e;
// multiply larger value, and reduce its exponent accordingly,
// to get matching exponents
const newL = infNum(l.v * (10n ** expDiff), l.e - expDiff);
// ensure we return the args in the same order
if (swapped) {
return [newL, s];
}
return [s, newL];
}
// more optimized way to normalize this number of InfNums with each other
// no loops, and minimum number of if statements
// the first arg, only, is copied and returned
function normInPlaceInfNum(argA, b, c, d, e, f) {
let a = copyInfNum(argA);
// assume they do not already all have same the exponent to save all the checking
let smallestExponent = a.e;
if (b.e < smallestExponent) {
smallestExponent = b.e;
}
if (c.e < smallestExponent) {
smallestExponent = c.e;
}
if (d.e < smallestExponent) {
smallestExponent = d.e;
}
if (e.e < smallestExponent) {
smallestExponent = e.e;
}
if (f.e < smallestExponent) {
smallestExponent = f.e;
}
// multiply all values by 10^diff, and reduce each exponent accordingly,
// to get all matching exponents
let expDiff = a.e - smallestExponent;
a.v = a.v * (10n ** expDiff);
a.e = a.e - expDiff;
expDiff = b.e - smallestExponent;
b.v = b.v * (10n ** expDiff);
b.e = b.e - expDiff;
expDiff = c.e - smallestExponent;
c.v = c.v * (10n ** expDiff);
c.e = c.e - expDiff;
expDiff = d.e - smallestExponent;
d.v = d.v * (10n ** expDiff);
d.e = d.e - expDiff;
expDiff = e.e - smallestExponent;
e.v = e.v * (10n ** expDiff);
e.e = e.e - expDiff;
expDiff = f.e - smallestExponent;
f.v = f.v * (10n ** expDiff);
f.e = f.e - expDiff;
return a;
}
// copies values from a and b, so the given objects are never modified
function infNumAdd(a, b) {
const norm = normInfNum(a, b);
return infNum(norm[0].v + norm[1].v, norm[0].e);
}
// assumes arguments have the same exponent
function infNumAddNorm(a, b) {
return infNum(a.v + b.v, a.e);
}
// copies values from a and b, so the given objects are not modified
function infNumSub(a, b) {
const norm = normInfNum(a, b);
return infNum(norm[0].v - norm[1].v, norm[0].e);
}
// assumes arguments have the same exponent
function infNumSubNorm(a, b) {
return infNum(a.v - b.v, a.e);
}
function infNumDiv(argA, argB, precis) {
// - multiply “top” value by 10^precision
// - divide (throw away remainder), then
// - subtract precision from exponent
const p = BigInt(precis);
// multiply “top” value by 10^precision
let a = infNumMul(argA, infNum(10n ** p, 0n));
const norm = normInfNum(a, argB);
a = norm[0];
let b = norm[1];
// divide (throws away remainder)
var truncated = infNum(a.v / b.v, a.e - b.e);
// subtract precision from exponent
truncated.e -= p;
// divide then multiply the value portion by 10^(power-precis)
// (power is n.v.toString().length)
// i assume there's no better way to get log10(truncated.v)?
const power = truncated.v.toString().length;
if (power <= precis) {
return truncated;
}
let truncPower = 10n ** BigInt(power-precis);
truncated.v /= truncPower;
truncated.v *= truncPower;
return truncated;
}
function infNumEq(a, b) {
const normalized = normInfNum(a, b);
return normalized[0].v === normalized[1].v;
}
function infNumLt(a, b) {
if (a.v < b.v && a.e <= b.e) {
return true;
} else if (a.v === 0n) {
if (b.v <= 0n) {
return false;
} else {
return true;
}
} else if (b.v === 0n) {
if (a.v < 0n) {
return true;
} else {
return false;
}
}
const normalized = normInfNum(a, b);
return normalized[0].v < normalized[1].v;
}
function infNumLe(a, b) {
const normalized = normInfNum(a, b);
return normalized[0].v <= normalized[1].v;
}
function infNumGt(a, b) {
if (a.v > b.v && a.e >= b.e) {
return true;
} else if (a.v === 0n) {
if (b.v < 0n) {
return true;
} else {
return false;
}
} else if (b.v === 0n) {
if (a.v < 0n) {
return false;
} else {
return true;
}
}
const normalized = normInfNum(a, b);
return normalized[0].v > normalized[1].v;
}
function infNumGe(a, b) {
const normalized = normInfNum(a, b);
return normalized[0].v >= normalized[1].v;
}
// assumes the argumments have the same exponent
function infNumGtNorm(a, b) {
return a.v > b.v;
}
function infNumApproxEq(a, b, precis) {
// if (a.v === 0n && b.v === 0n) {
// return true;
// }
// if (a.v > 0n && b.v < 0n) {
// return false;
// }
// if (a.v < 0n && b.v > 0n) {
// return false;
// }
const norm = normInfNum(a, b);
const diff = infNumAbs(infNumSubNorm(norm[0], norm[1]));
return infNumLt(diff, infNum(1n, (BigInt(a.v.toString().length) + a.e) - BigInt(precis)));
//return infNumLt(diff, infNum(1n, BigInt(-precis)));
// const norm = normInfNum(a, b);
//
// const aStr = norm[0].v.toString().substring(0, precis);
// // after normalizing (ensuring exponents are the same)
// // if one of the values has fewer digits than the
// // requested precision, both values must be equal
// if (aStr.length < precis) {
// return norm[0].v === norm[1].v;
// }
// const bStr = norm[1].v.toString().substring(0, precis);
// if (bStr.length < precis) {
// return norm[0].v === norm[1].v;
// }
//
// return aStr === bStr;
}
function infNumApproxEqSimple(a, b, precis) {
const norm = normInfNum(a, b);
norm[0] = infNumTruncateToLen(norm[0], precis);
norm[1] = infNumTruncateToLen(norm[1], precis);
return infNumEq(norm[0], norm[1]);
}
function infNumToString(n) {
var value = n.v.toString();
if (n.e === 0n) {
return value;
}
if (n.e > 0n) {
let i = 0n;
while (i < n.e) {
value = value + "0";
i = i + 1n;
}
return value;
}
var i = 0n;
var dec = "";
var neg = false;
if (value.startsWith("-")) {
neg = true;
value = value.substr(1);
}
while (i > n.e) {
if (value.length > 0) {
dec = value.slice(-1) + dec;
value = value.slice(0, -1);
} else {
dec = "0" + dec;
}
i = i - 1n;
}
if (value.length == 0) {
value = "0";
}
if (neg) {
value = "-" + value;
}
return trimZeroes(value + "." + dec);
}
function infNumExpString(n) {
return infNumExpStringTruncToLen(n, -1);
}
function infNumExpStringTruncToLen(n, truncDecimals) {
var value = n.v.toString();
let negative = false;
if (n.v < 0) {
negative = true;
value = value.substring(1);
}
let bd = value.length;
let ad = value.length - 1;
let finalExponent = n.e + BigInt(ad);
let decimal = trimZeroes(value.substring(0, 1) + "." + value.substring(1));
if (!decimal.includes(".")) {
decimal = decimal + ".0";
}
if (truncDecimals > 0) {
decimal = decimal.substring(0, truncDecimals + 2);
}
if (negative) {
decimal = "-" + decimal;
}
return decimal + "e" + finalExponent.toString();
}
function createInfNumFromExpStr(s) {
const split = s.split("e");
const decSplit = split[0].split(".");
let exp = BigInt(split[1]);
exp -= BigInt(decSplit[1].length);
let val = BigInt(decSplit[0] + decSplit[1]);
return infNum(val, exp);
}
// this is not suitable for displaying to users (it's in base 16)
// divides the value portion of n as long as it's divisible by 10
function infNumFastStr(n) {
let nCopy = copyInfNum(n);
while (nCopy.v % 10n === 0n && nCopy.v !== 0n) {
nCopy.v /= 10n;
nCopy.e += 1n;
}
// using radix 16 because in testing it was 75% faster than
// radix 10 and 32
return nCopy.v.toString(16) + "E" + nCopy.e.toString(16);
}
function createInfNumFromFastStr(s) {
const split = s.split("E");
let negative = false;
if (split[0].startsWith("-")) {
negative = true;
split[0] = split[0].substring(1);
}
let val = BigInt("0x" + split[0]);
if (negative) {
val = val * -1n;
}
negative = false;
if (split[1].startsWith("-")) {
negative = true;
split[1] = split[1].substring(1);
}
let exp = BigInt("0x" + split[1]);
if (negative) {
exp = exp * -1n;
}
return infNum(val, exp);
}
// this was the version used until v0.9.0
function infNumTruncateToLenv090(n, len) {
var truncatedExpString = infNumExpStringTruncToLen(n, len-1);
return createInfNum(truncatedExpString);
}
function infNumTruncateToLenOldMaybeBad(n, len) {
var a = copyInfNum(n);
const orig = a.v.toString();
if (orig.length <= len) {
return a;
}
a.v = BigInt(a.v.toString().substring(0,len));
a.e = a.e + BigInt(orig.length - len);
return a;
}
function infNumTruncateToLenNoString(n, len) {
let result = infNum(n.v, n.e);
let negative = result.v < 0n;
if (negative) {
result.v *= -1n;
}
let pow = 10n ** BigInt(len);
while (result.v > pow) {
result.v /= 10n;
result.e += 1n;
}
if (negative) {
result.v *= -1n;
}
return result;
}
// faster version added after v0.9.0
function infNumTruncateToLen(n, len) {
let result = infNum(n.v, n.e);
let negative = result.v < 0n;
if (negative) {
result.v *= -1n;
}
let pow = 10n ** BigInt(len+15);
while (result.v > pow) {
result.v /= 10000000000000000n;
result.e += 16n;
}
pow = 10n ** BigInt(len+3);
while (result.v > pow) {
result.v /= 10000n;
result.e += 4n;
}
pow = 10n ** BigInt(len);
while (result.v > pow) {
result.v /= 10n;
result.e += 1n;
}
if (negative) {
result.v *= -1n;
}
return result;
}
// 123456, 2 -> 120000
function infNumTruncateToLenFastPow2(n, len) {
let result = infNum(n.v, n.e);
let negative = result.v < 0n;
if (negative) {
result.v *= -1n;
}
let pow = 10n ** BigInt(len+1);
while (result.v > pow) {
result.v /= 100n;
result.e += 2n;
}
pow = 10n ** BigInt(len);
while (result.v > pow) {
result.v /= 10n;
result.e += 1n;
}
if (negative) {
result.v *= -1n;
}
return result;
}
// shortened version of infNumExpStringTruncToLen()
function infNumMagnitude(n) {
var value = n.v.toString();
// anything after 1st digit is "after decimal"
let afterDecimal = n.v < 0 ? value.length - 2 : value.length - 1;
let finalExponent = parseInt(n.e) + afterDecimal;
return finalExponent;
}
function infNumAbs(n) {
if (n.v < 0) {
return infNum(-n.v, n.e);
}
return n;
}
//
// Math.sqrt(2*(10**7)) === Math.sqrt(2) * (10**3.5)
//
// 10**3.5 === 10**0.5 * 10**3
//
// Math.sqrt(2*(10**7)) === Math.sqrt(2) * 10**0.5 * 10**3
//
// use "var" here instead of "const" to keep the browser from complaining
// about re-declaring it
var infNumSqrt10 = infNum(31622776601683795n, -16n);
function infNumRoughSqrt(a) {
if (a.v === 0n) {
return a;
}
// we want to keep exponent an integer, so we must
// check whether it's even before dividing by 2
if (a.e % 2n === 0n) {
return {
v: bigIntRoughSqrt(a.v),
e: a.e >> 1n
};
} else {
return {
v: bigIntRoughSqrt(a.v * 10n),
e: a.e >> 1n
};
}
}
// rough but hopefully fast sqrt(BigInt)
// principal:
// Math.sqrt(4000) === Math.sqrt(10**3) * Math.sqrt(4)
// Math.sqrt(4000) === (10**(3/2)) * Math.sqrt(4)
// Math.sqrt(4000) === (10**1) * (10**0.5) * Math.sqrt(4)
function bigIntRoughSqrt(a) {
if (a < 0n) {
throw "cannot take rough square root of negative value";
}
let digits = a.toString().length;
const mag = digits - 1;
//const magMinusTwo = mag - 2;
//let mantissa = null;
//if (magMinusTwo < 0) {
// // get first three digits of value
// // 5 (v:5n,e:0n) is magnitude 0
// // (5n * (10n**(-2n*-1n))) / (10n**(0n*-1n)) => 500n
// // 0.054321 (v:54321n,e:-6n) is magnitude -2
// // (54321n * (10n**(-4n*-1n))) / (10n**(-6n*-1n)) => 543n
// mantissa = (a.v * (10n**BigInt(magMinusTwo*-1))) / (10n**(a.e*-1n));
//} else {
// // get first three digits of value
// // 398765 is magnitude 5
// // 398765n / (10n**(5n-2n)) => 398n
// mantissa = a.v / (10n**BigInt(magMinusTwo));
//}
//const floatMantissa = parseFloat(mantissa) / 100.0;
//return floatMantissa;
// make a copy of the argument (necessary?)
let mantissa = a * 10n;
digits++;
while (mantissa < 100n) {
mantissa *= 10n;
digits++;
}
// keep first 3 digits of mantissa
mantissa = mantissa / (10n**BigInt(digits - 3));
const floatMantissa = parseFloat(mantissa) / 100.0;
// to perform square root, we are dividing magnitude in half
// if magnitude is not an even number, multiply by 3, which is
// roughly the square root of 10, since:
// 10**3.5 === 10**0.5 * 10**3
const sqrt1000 = mag % 2 === 0 ?
BigInt(Math.round(Math.sqrt(floatMantissa) * 1000.0)) * (10n**(BigInt(mag/2)))
:
BigInt(Math.round(Math.sqrt(floatMantissa) * 1000.0)) * (10n**(BigInt(Math.floor(mag/2)))) * 3n;
return sqrt1000 / BigInt(1000n);
}
// using more digits of precision:
// - seems to decrease the error by 10^(digts/2)
// - exponentially slows down the computation
//
// testing on Apple M1 processor (single-core presumably)
// where 4 million square roots of inputs of varying lengths are taken:
// - with 2 additional digits of precision:
// - ~2e-3% average error
// - this required, on average, 1.44 iterations of Heron's method per square root
// - run time of 1.27s (about 22% faster than with 6 digits of precision)
// - with 6 additional digits of precision:
// - ~2e-5% average error
// - this required, on average, 1.65 iterations of Heron's method per square root
// - run time of 1.56s
// - with 10 additional digits of precision:
// - ~2e-7% average error
// - this required, on average, 1.88 iterations of Heron's method per square root
// - run time of 1.86s (about 18% slower than with 6 digits of precision)
// - with 14 additional digits of precision:
// - ~2e-9% average error
// - this required, on average, 2.16 iterations of Heron's method per square root
// - run time of 2.24s (about 42% slower than with 6 digits of precision)
// - with 18 additional digits of precision:
// - ~2e-11% average error
// - this required, on average, 2.37 iterations of Heron's method per square root
// - run time of 2.93s (about 88% slower than with 6 digits of precision)
// - with 22 additional digits of precision:
// - ~2e-13% average error
// - this required, on average, 2.58 iterations of Heron's method per square root
// - run time of 3.70s (about 237% slower than with 6 digits of precision)
function infNumSqrtHerons(a) {
if (a.v === 0n) {
return a;
}
// we want to keep exponent an integer, so we must
// check whether it's even before dividing by 2
if (a.e % 2n === 0n) {
return {
v: bigIntSqrtHerons(a.v * 10000000000n), // increase by 10^10, and reduce exponent accordingly before halving
e: (a.e - 10n) >> 1n
};
} else {
return {
v: bigIntSqrtHerons(a.v * 100000000000n), // increase by 10^11 here, and reduce exponent accordingly before halving
e: (a.e - 11n) >> 1n
};
}
}
function infNumSqrtHeronsLessPrecis(a) {
if (a.v === 0n) {
return a;
}
// we want to keep exponent an integer, so we must
// check whether it's even before dividing by 2
if (a.e % 2n === 0n) {
return {
v: bigIntSqrtHerons(a.v * 1000000n), // increase by 10^6, and reduce exponent accordingly before halving
e: (a.e - 6n) >> 1n
};
} else {
return {
v: bigIntSqrtHerons(a.v * 10000000n), // increase by 10^7 here, and reduce exponent accordingly before halving
e: (a.e - 7n) >> 1n
};
}
}
function infNumSqrtHeronsMorePrecis(a) {
if (a.v === 0n) {
return a;
}
// we want to keep exponent an integer, so we must
// check whether it's even before dividing by 2
if (a.e % 2n === 0n) {
return {
v: bigIntSqrtHerons(a.v * 100000000000000n), // increase by 10^14, and reduce exponent accordingly before halving
e: (a.e - 14n) >> 1n
};
} else {
return {
v: bigIntSqrtHerons(a.v * 1000000000000000n), // increase by 10^15 here, and reduce exponent accordingly before halving
e: (a.e - 15n) >> 1n
};
}
}
// based on Heron's method: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots
// also thanks to: https://stackoverflow.com/a/9236307/259456
//
// sqrt(n) = sqrt(f * 2^2m) = sqrt(f)*2^m
//
// to begin Heron's method iterations, we just need a
// decent starting guess. the better the guess, the
// fewer iterations need to be done.
//
// to convert the bigint into f * 2^2m:
// 123456789 ~= 1234 * 10^5
// since the power 10 is raised to is odd,
// we move one multiple of 10:
// 1234 * 10^5 = 12340 * 10^4
//
// since we can use ~17 decimal digits with built-in
// JavaScript floats without losing precision, and
// since we may need to multiply the float value
// by 10, we'll use the first 16 decimal digits to
// create a float value, upon which JavaSript's
// Math.sqrt() can be used.
//
// then by:
// sqrt(n) = sqrt(f * 2^2m) = sqrt(f)*2^m
//
// we just need to multiply that square root by 2^m
//
// that gives us our starting guess for Heron's method
// iterations
//
function bigIntSqrtHerons(a) {
if (a < 0n) {
throw "cannot take square root of negative value";
}
const decimalStr = a.toString(10);
const tenPowerInitial = decimalStr.length - 16;
const roughFloatInitial = tenPowerInitial <= 0 ? Number(a) : parseFloat(decimalStr.substring(0,16));
const oddInitialPower = (tenPowerInitial & 1) === 1;
let tenPower = 0;
if (tenPowerInitial > 0) {
//tenPower = oddInitialPower ? (tenPowerInitial - 1) / 2 : (tenPowerInitial / 2);
tenPower = tenPowerInitial >> 1;
}
const roughFloat = (tenPowerInitial > 0 && oddInitialPower) ? roughFloatInitial * 10 : roughFloatInitial;
let nextGuess = BigInt(Math.floor(Math.sqrt(roughFloat))) * (10n ** BigInt(tenPower));
let currentGuess;
let guessDiff;
do {
currentGuess = nextGuess;
// average of currentGuess and (a/currentGuess)
nextGuess = (currentGuess + (a/currentGuess)) >> 1n;
guessDiff = currentGuess - nextGuess;
//++heronsIterations;
} while (guessDiff > 1n || guessDiff < -1n);
return nextGuess;
}
// remove starting here for minify
if (doUnitTests) {
const runUnitTest = function(testFn) {
if (!testFn()) {
console.log("unit test FAILED:\n" + testFn.toString());
}
}
runUnitTest(function() {
return trimZeroes("50000") === "50000";
});
runUnitTest(function() {
return trimZeroes("050") === "50";
});
runUnitTest(function() {
return trimZeroes("-050") === "-50";
});
runUnitTest(function() {
return trimZeroes("-022.00") === "-22";
});
runUnitTest(function() {
return trimZeroes("022.002200") === "22.0022";
});
runUnitTest(function() {
return trimZeroes("-22.002200") === "-22.0022";
});
runUnitTest(function() {
return trimZeroes("000.002200") === "0.0022";
});
runUnitTest(function() {
return trimZeroes("-.0022") === "-0.0022";
});
runUnitTest(function() {
return trimZeroes("5.") === "5";
});
runUnitTest(function() {
return infNumEq(createInfNum("0.0"), infNum(0n, 0n));
});
runUnitTest(function() {
return infNumEq(createInfNum("0"), infNum(0n, 0n));
});
runUnitTest(function() {
return infNumEq(createInfNum("123"), infNum(123n, 0n));
});
runUnitTest(function() {
return infNumEq(createInfNum("123.456"), infNum(123456n, -3n));
});
runUnitTest(function() {
return infNumEq(createInfNum(" 3 "), infNum(3n, 0n));
});
runUnitTest(function() {
return infNumEq(createInfNum(" 123456789.000000000012345"), infNum(123456789000000000012345n, -15n));
});
runUnitTest(function() {
return infNumEq(createInfNum(" -4.00321"), infNum(-400321n, -5n));
});
runUnitTest(function() {
return infNumEq(createInfNum(" -0.009 "), infNum(-9n, -3n));
});
runUnitTest(function() {
return infNumEq(createInfNum("123e4"), infNum(123n, 4n));
});
runUnitTest(function() {
return infNumEq(createInfNum("123e4"), infNum(123n, 4n));
});
runUnitTest(function() {
return infNumEq(createInfNum("1.23e4"), infNum(123n, 2n));
});
runUnitTest(function() {
return infNumEq(createInfNum("5. E22"), infNum(5n, 22n));
});
runUnitTest(function() {
return infNumEq(createInfNum(" 1.23 e -10"), infNum(123n, -12n));
});
runUnitTest(function() {
return infNumEq(createInfNum(" 1,234 E -10"), infNum(1234n, -10n));
});
runUnitTest(function() {
return infNumEq(infNumMul(createInfNum("100"), createInfNum("1.5")), infNum(1500n, -1n));
});
runUnitTest(function() {
return infNumEq(infNumMul(createInfNum("123.5"), createInfNum("1.5")), infNum(18525n, -2n));
});
runUnitTest(function() {
return infNumEq(infNumMul(createInfNum("15000"), createInfNum("0.0006")), infNum(9n, 0n));
});
let origTestA, origTestB;
let testA = createInfNum("100"); origTestA = copyInfNum(testA);
let testB = createInfNum("123.456"); origTestB = copyInfNum(testB);
let testNorm = normInfNum(testA, testB);
runUnitTest(function() { return infNumEq(testNorm[0], origTestA); });
runUnitTest(function() { return infNumEq(testNorm[1], origTestB); });
runUnitTest(function() { return testNorm[0].e === testNorm[1].e; });
testA = createInfNum("0.0321"); origTestA = copyInfNum(testA);
testB = createInfNum("5"); origTestB = copyInfNum(testB);
testNorm = normInfNum(testA, testB);
runUnitTest(function() { return infNumEq(testNorm[0], origTestA); });
runUnitTest(function() { return infNumEq(testNorm[1], origTestB); });
runUnitTest(function() { return testNorm[0].e === testNorm[1].e; });
testA = createInfNum("22"); origTestA = copyInfNum(testA);
testB = createInfNum("5"); origTestB = copyInfNum(testB);
testNorm = normInfNum(testA, testB);
runUnitTest(function() { return infNumEq(testNorm[0], origTestA); });
runUnitTest(function() { return infNumEq(testNorm[1], origTestB); });
runUnitTest(function() { return testNorm[0].e === testNorm[1].e; });
let origTestC, origTestD, origTestE, origTestF;
testA = infNum(5n, -2n); origTestA = copyInfNum(testA);
testB = infNum(5n, -1n); origTestB = copyInfNum(testB);
let testC = infNum(5n, 0n); origTestC = copyInfNum(testC);
let testD = infNum(5n, 1n); origTestD = copyInfNum(testD);
let testE = infNum(5n, 2n); origTestE = copyInfNum(testE);
let testF = infNum(5n, 3n); origTestF = copyInfNum(testF);
normA = normInPlaceInfNum(testA, testB, testC, testD, testE, testF);
runUnitTest(function() { return infNumEq(testA, origTestA); });
runUnitTest(function() { return infNumEq(testB, origTestB); });
runUnitTest(function() { return infNumEq(testC, origTestC); });
runUnitTest(function() { return infNumEq(testD, origTestD); });
runUnitTest(function() { return infNumEq(testE, origTestE); });
runUnitTest(function() { return infNumEq(testF, origTestF); });
runUnitTest(function() { return normA.e === testB.e; });
runUnitTest(function() { return normA.e === testC.e; });
runUnitTest(function() { return normA.e === testD.e; });
runUnitTest(function() { return normA.e === testE.e; });
runUnitTest(function() { return normA.e === testF.e; });
testA = infNum(5n, -2n); origTestA = copyInfNum(testA);
testB = infNum(5n, -11n); origTestB = copyInfNum(testB);
testC = infNum(5n, -3n); origTestC = copyInfNum(testC);
testD = infNum(5n, -22n); origTestD = copyInfNum(testD);
testE = infNum(5n, -2n); origTestE = copyInfNum(testE);
testF = infNum(5n, -5n); origTestF = copyInfNum(testF);
normA = normInPlaceInfNum(testA, testB, testC, testD, testE, testF);
runUnitTest(function() { return infNumEq(testA, origTestA); });
runUnitTest(function() { return infNumEq(testB, origTestB); });
runUnitTest(function() { return infNumEq(testC, origTestC); });
runUnitTest(function() { return infNumEq(testD, origTestD); });
runUnitTest(function() { return infNumEq(testE, origTestE); });
runUnitTest(function() { return infNumEq(testF, origTestF); });
runUnitTest(function() { return normA.e === testB.e; });
runUnitTest(function() { return normA.e === testC.e; });
runUnitTest(function() { return normA.e === testD.e; });
runUnitTest(function() { return normA.e === testE.e; });
runUnitTest(function() { return normA.e === testF.e; });
testA = infNum(5n, 2n); origTestA = copyInfNum(testA);
testB = infNum(5n, 11n); origTestB = copyInfNum(testB);
testC = infNum(5n, 3n); origTestC = copyInfNum(testC);
testD = infNum(5n, 22n); origTestD = copyInfNum(testD);
testE = infNum(5n, 2n); origTestE = copyInfNum(testE);
testF = infNum(5n, 5n); origTestF = copyInfNum(testF);
normA = normInPlaceInfNum(testA, testB, testC, testD, testE, testF);
runUnitTest(function() { return infNumEq(testA, origTestA); });
runUnitTest(function() { return infNumEq(testB, origTestB); });
runUnitTest(function() { return infNumEq(testC, origTestC); });
runUnitTest(function() { return infNumEq(testD, origTestD); });
runUnitTest(function() { return infNumEq(testE, origTestE); });
runUnitTest(function() { return infNumEq(testF, origTestF); });
runUnitTest(function() { return testA.e === testB.e; });
runUnitTest(function() { return testA.e === testC.e; });
runUnitTest(function() { return testA.e === testD.e; });
runUnitTest(function() { return testA.e === testE.e; });
runUnitTest(function() { return testA.e === testF.e; });
// 100 + 1.5 = 101.5
runUnitTest(function() {
return infNumEq(infNumAdd(createInfNum("100"), createInfNum("1.5")), infNum(1015n, -1n));
});
// 123 + 0.456 = 123.456
runUnitTest(function() {
return infNumEq(infNumAdd(createInfNum("123"), createInfNum("0.456")), infNum(123456n, -3n));
});
// 0.00001 + 5.05 = 5.05001
runUnitTest(function() {
return infNumEq(infNumAdd(createInfNum("0.00001"), createInfNum("5.05")), infNum(505001n, -5n));
});