LENGTH
This page runs a BASIC program that estimates the length of a curve, the parabola \(y = x^2\) from \(x = 0\) to \(x = 1\). The program is rewritten in Python and runs right here in your browser. Edit the code and press Run to run it again; Reset brings back the original program.
The idea is to replace the curve by \(n\) straight segments that join points on it. The loop finds the two ends of segment k, at xl and xr, and uses the Pythagorean theorem to get its length:
\[ \text{segment} = \sqrt{(x_r - x_l)^2 + (y_l - y_r)^2}. \]
Each pass adds that length to total and prints k and the segment’s length; at the end the program prints n and the total. With n = 2 the estimate is about 1.4604. The true length is about 1.4789, and the chain of segments always comes out a little shorter than the curve, because a straight segment is the shortest path between its ends. Try n = 10, 100, and 1000 to watch the total close in on 1.4789, or change fnf to measure a different curve.
A few BASIC habits translate differently. QBasic lets a FUNCTION be written at the end of the program, after the code that uses it. Python needs a function to be defined before it is called, so in the Python the def comes first, and return gives back the value that BASIC sets with fnf = .... SQR is BASIC’s square root; in Python it is math.sqrt, which needs import math at the top. BASIC’s ^ for powers is ** in Python. Finally, QBasic quietly starts every variable at 0, so the original never sets total = 0; Python stops with an error if a variable is used before it has a value, so the Python sets it before the loop.
Notes from the textbook
Add notes here.
1 DEFDBL A-Z
2 xinitial = 0
3 xfinal = 1
4 n = 2
5 deltax = (xfinal - xinitial) / n
6 FOR k = 1 TO n
7 xl = xinitial + (k - 1) * deltax
8 xr = xinitial + k * deltax
9 yl = fnf(xl)
10 yr = fnf(xr)
11 segment = SQR((xr - xl) ^ 2 + (yl - yr) ^ 2)
12 total = total + segment
13 PRINT k, segment
14 NEXT k
15 PRINT n, total
16 FUNCTION fnf (x)
17 fnf = x ^ 2
18 END FUNCTION
Output
Everything the program prints appears here, one line for each print(...),
like BASIC's PRINT. Numbers printed on the same line are lined up in columns.
Python code
Press Run (or Ctrl/⌘ + Enter) to run the program again. Press Esc, then Tab, to leave the editor.