2 ms·
The idea is nice, but the code is a little flaky. For example, change the number of decimals from 1000 to 2000 and it enters an infinite loop, but 4000 works a
by sltkr 14y ago
The idea is nice, but the code is a little flaky. For example, change the number of decimals from 1000 to 2000 and it enters an infinite loop, but 4000 works again. This occurs because due to rounding a and b might not converge to the exact same value.
A more reliable way to write the algorithm is this:
n = 0
while not almosteq(a, b):
n, a, b = n + 1, (a + b)/2, sqrt(a*b)
series += 2**(n+1) * (a*a - b*b)
- johndcook 14y agoGood catch. I updated the post so that it tests for a > b + epsilon instead of a == b.