Michael Calkins (Login MCalkins) Moderator Posted Apr 20, 2012 12:21 PM

Yes, I am serious.

I guess if you want to be prejudiced against a perfectly good programming construct, I guess that's your business. However, I am quite sure that using a loop is vastly superior to using a recursive function in this instance.

Given the fact that pi is found to near the precision limit of a DOUBLE within about 5 iterations, it is probably unnecessary to really exceed that.

However, here is the program using a loop. It should be vastly more efficient in both space and time:

count = 200 is silly, but it demonstrates the lack of stack constraint.

Regards,
Michael

DIM PI AS DOUBLE
DIM A AS DOUBLE
DIM B AS DOUBLE
DIM C AS DOUBLE
DIM oA AS DOUBLE
DIM count AS LONG
DIM n AS LONG

CLS
n = 0
PI = 0#: A = 1#: B = SQR(1# / 2#): C = 1# / 4#

count = 200

DO UNTIL n >= count
PI = ((A + B) ^ 2#) / (4# * C)
C = C - 2# ^ n * (((A - B) / 2#) ^ 2#)
oA = A
A = (A + B) / 2#
B = SQR(oA * B)
n = n + 1
LOOP
PRINT PI