-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomputesqrt2.html
58 lines (56 loc) · 1.72 KB
/
computesqrt2.html
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
<html>
<head>
<title>Compute square root of 2 digits using BigInt</title>
</head>
<script>
const one = BigInt(1);
const ten = BigInt(10);
const twenty = BigInt(20);
const hundred = BigInt(100);
// Adapted from https://rosettacode.org/wiki/Square_root_by_hand
class ComputeSQRT {
constructor(val = 2) {
this.val = BigInt(val);
this.j = BigInt(Math.floor(Math.sqrt(val)));
this.k = BigInt(this.j);
this.d = BigInt(this.j);
this.digitsYielded = 0;
}
yieldDigit() {
this.val = hundred * (this.val - this.k * this.d);
this.k = twenty * this.j;
for(let d = one; d <= ten; d++) {
if (this.val < (this.k + d) * d) {
this.d = d - one;
this.j = ten * this.j + this.d;
this.k += this.d;
this.digitsYielded += 1;
return this.d;
}
}
}
}
function configureSpigot() {
let spigot = new ComputeSQRT();
const maxDigits = 1e4;
const maxDuration = 5;
let sqrt = "<math><msqrt><mi>2</mi></msqrt></math>=1.";
const computeDigits = function() {
const start = performance.now();
while (spigot.digitsYielded < maxDigits && performance.now() - start < maxDuration) {
sqrt += spigot.yieldDigit() + "­";
}
if (spigot.digitsYielded >= maxDigits) {
sqrt += "...";
}
document.body.innerHTML = sqrt;
if (spigot.digitsYielded < maxDigits) {
window.requestAnimationFrame(computeDigits);
}
};
computeDigits();
}
</script>
<BODY onload="configureSpigot()">
<math><msqrt><mi>2</mi></msqrt></math>=1.4142... (to be overwritten by the script)</BODY>
</html>