PDA

View Full Version : A QBasic Program that calculates . . .



37818
12-20-2014, 05:18 PM
Just for fun, see if you can guess what this program calculates:


A# = 1#
B# = .5#
C# = SQR(2#) / 2#
D# = .25#
LblA:
E# = A#
B# = 2# * B#
A# = (A# + C#) / 2#
C# = SQR(E# * C#)
D# = D# - B# * (A# - E#) * (A# - E#)
oldx# = x#
x# = (A# + C#) * (A# + C#) / (4# * D#)
PRINT x#
IF oldx# <> x# THEN GOTO LblA
SYSTEM

Cow Poke
12-20-2014, 06:13 PM
a range of prime numbers?

Leonhard
12-21-2014, 08:54 AM
Just for fun, see if you can guess what this program calculates:


A# = 1#
B# = .5#
C# = SQR(2#) / 2#
D# = .25#
LblA:
E# = A#
B# = 2# * B#
A# = (A# + C#) / 2#
C# = SQR(E# * C#)
D# = D# - B# * (A# - E#) * (A# - E#)
oldx# = x#
x# = (A# + C#) * (A# + C#) / (4# * D#)
PRINT x#
IF oldx# <> x# THEN GOTO LblA
SYSTEM

Its honestly been a while since I've last looked at QBASIC code. I'm not sure why you're willing to torture yourself with it, but let me get a QBASIC interpreter and see what this code actually does, before trying to guess what it does.

Leonhard
12-21-2014, 09:32 AM
Ah wait, this is recognisable now. Its the Gauss-Legendre's quadratic algorithm for calculating pi.

You should still initisalise x even though grabbing something random off the memory stack probably won't make oldx match x.

And its prettier in C.



int main()
{
double a = 1.0, b = 0.5, c = sqrt(2.0)/2, d = 1.0/4, e, x = 0.0, oldx;

do {
e = a;
b = 2*b;
a = (a+c)/2;
c = sqrt(e*c);
d = d - b * (a - e) * (a - e);
oldx = x;
x = (a + c) * (a + c) / (4 * d);
fprintf(stdout,"%f\n",x);
}
while (x != oldx)

return 0;
}