TAYLOR

In review

This page runs a BASIC program that graphs the Taylor polynomial of degree 17 for \(\sin x\),

\[ x - \frac{x^3}{3!} + \frac{x^5}{5!} - \cdots + \frac{x^{17}}{17!}, \]

from \(x = 0\) to \(x = 3.14\). The program is rewritten in Python and runs right here in your browser. Edit the code and press Run to redraw the graph; Reset brings back the original program.

The program has two functions. fnfact(m) computes \(m!\) by multiplying 2, 3, …, m together. fnpoly(x) builds the polynomial term by term: it starts the sum at x, then for k = 3, 5, 7, …, 17 adds Sign * x ^ k / fnfact(k), flipping Sign between −1 and +1 each time so the terms alternate. The main loop steps x across the window by 0.01 and draws a segment from \((x, \text{fnpoly}(x))\) to the next point. WINDOW (0, -1.5)-(3.14, 1.5) sets x from 0 to 3.14 across and y from −1.5 to 1.5 up.

On this interval the polynomial is so close to \(\sin x\) that you couldn’t tell them apart. To see where it fails, widen the window and the loop, say to 10 or 12, and lower the 17 in range(3, 18, 2) to get fewer terms. To compare with the real thing, add a second line inside the loop, line((x, math.sin(x)), (x + 0.01, math.sin(x + 0.01)), 4), with import math at the top; the last number draws it in red.

Two things change in Python. 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 = .... And BASIC’s FOR x = 0 TO 3.14 STEP .01 counts in steps of 0.01, but Python’s range only counts in whole numbers, so the Python uses a while loop that adds 0.01 to x each time. Likewise FOR k = 3 TO 17 STEP 2 becomes range(3, 18, 2), since range stops just before its second number.

Notes from the textbook

Add notes here.

 1  DEFDBL A-Z
 2  SCREEN 12
 3  WINDOW (0, -1.5)-(3.14, 1.5)
 4  FOR x = 0 TO 3.14 STEP .01
 5          LINE (x, fnpoly(x))-(x + .01, fnpoly(x + .01))
 6  NEXT x
 7  FUNCTION fnfact (m)
 8          P = 1
 9          FOR r = 2 TO m
10                  P = P * r
11          NEXT r
12          fnfact = P
13  END FUNCTION
14  FUNCTION fnpoly (x)
15          Sum = x
16          Sign = -1
17          FOR k = 3 TO 17 STEP 2
18                  Sum = Sum + Sign * x ^ k / fnfact(k)
19                  Sign = (-1) * Sign
20          NEXT k
21          fnpoly = Sum
22  END FUNCTION

Graph

Each line(...) draws one straight segment, like BASIC's LINE, and window(...) sets the visible range, like WINDOW. Hover over the graph to read coordinates.

Loading Python. The first run takes a few seconds.

Python code

Press Run (or Ctrl/⌘ + Enter) to redraw the graph. Press Esc, then Tab, to leave the editor.

Loading Python…