var pi = document.getElementById("pi");
function * calcpi(){
let q = 1;
let r = 0;
let t = 1;
let k = 1;
let n = 3;
let l = 3;
while (true){
if (4*q+r-t < n*t){
alert(n);
yield n;
nr = 10*(r-n*t);
n = Math.floor((10*(3*q+r))/t)-10*n;
q *= 10;
r = nr;
} else {
nr = (2*q+r)*l;
nn = Math.floor((q*(7*k)+2+(r*l))/(t*l));
q *= k;
t *= l;
l += 2;
k += 1;
n = nn;
r = nr;
}
}
}
var pi_digits = calcpi();
var i = 0;
window.alert(pi_digits.next());
for (let j = 0; j < 10; j++){
pi.textContent += toString(pi_digits.next());
if (i == 100){
i = 0; pi.textContent+= "\n"
} else {
i += 1;
}
}
Pi: <br><span id="pi"></span>
I'm trying to get the first 100 digits of pi... I'm basing the code off of this https://replit.com/@Cloverwave/CalcPi?v=1 from https://rosettacode.org/wiki/Pi#Python Whenever I run this code my window gets alerted the right numbers, but it doesn't show those numbers on the page... I've been going off this: What's the yield keyword in JavaScript?
nvm I found the answer all I had to do was use .value behind .next() and remove the toString() function. Thanks to Bergi and this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield
<!DOCTYPE html>
<html>
<body>
Pi: <br><span id="pi"></span>
<script>
// window.alert("ok");
var pi = document.getElementById("pi");
function * calcpi(){
let q = 1;
let r = 0;
let t = 1;
let k = 1;
let n = 3;
let l = 3;
while (true){
if (4*q+r-t < n*t){
yield n;
nr = 10*(r-n*t);
n = Math.floor((10*(3*q+r))/t)-10*n;
q *= 10;
r = nr;
} else {
nr = (2*q+r)*l;
nn = Math.floor((q*(7*k)+2+(r*l))/(t*l));
q *= k;
t *= l;
l += 2;
k += 1;
n = nn;
r = nr;
}
}
}
var pi_digits = calcpi();
var i = 0;
for (let j = 0; j < 10; j++){
// window.alert("jo");
pi.textContent += pi_digits.next().value;
if (i == 100){
i = 0; pi.textContent += "\n"
} else {
i += 1;
}
}
//
</script>
</body>
</html>