In python I had this code to compute pi:
import os
color = lambda: os.system('COLOR f0')
color()
def otravez():
def calcPi(limit):
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
decimal = limit
counter = 0
while counter != decimal + 1:
if 4 * q + r - t < n * t:
yield n
if counter == 0:
yield '.'
if decimal == counter:
print('')
break
counter += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
def main():
pi_digits = calcPi(int(input("Dime el número de cifras que quieres conseguir de pi a continuación: ")))
for d in pi_digits:
print(d, end='', flush=True)
if __name__ == '__main__':
main()
print("¿Quieres calcular más dígitos?")
if input("Si es así escribe la palabra SI: ") == "SI":
clear = lambda: os.system('cls')
clear()
otravez()
otravez()
But trying to pass it to javascript doesn't work:
<html>
<head>
<div id="Pi"></div>
<meta charset="utf-8">
<title>Pi</title>
<script type="text/javascript">
function* calcPi(limit){
var q = 1;
var r = 0;
var t = 1;
var k = 1;
var n = 3;
var l = 3;
var nr = 0;
var nn = 0;
var decimal = limit;
var counter = 0;
while (counter != decimal + 1) {
if (4 * q + r - t < n * t) {
yield n;
if (counter == 0) {
yield '.';
};
if (decimal == counter) {
break;
};
counter += 1;
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(parseInt(prompt("Dime el número de cifras que quieres conseguir de pi a continuación: ")));
for (var number in pi_digits) {
document.getElementById('Pi').innerHTML += number;
};
</script>
</head>
<body>
</body>
</html>
I think it's a problem with iterators but I don't know how to fix it. It would be very helpful if someone could find out. Thanks.
The generator functions return an iterator iterator_functions you were calling it incorrectly, make some adjustments to your code, you can verify that the result is as expected. I hope it helps you