A645 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

A6 · Lesson 45 · Series in code

How a math library computes exp and sin

When you call math.exp(x), something has to turn x into a number, using only additions and multiplications. A Taylor series looks like the obvious answer: add terms until they're too small to matter. It mostly works, and in this lab you'll write it. But try it on e−20 and you get an answer three times too big, with every digit wrong. Floating-point arithmetic has only about 16 significant digits, and an alternating series with huge terms throws them away. Knowing when a series is safe to use in code is as important as knowing that it converges.

  • The curve shows the size of each term xnn! of the series for ex, on a log scale (each unit up is a factor of 10).
  • The terms grow until n≈x, then fall. For e−x the same terms appear with alternating signs, and they must cancel down to the tiny answer e−x.
  • The readout estimates how many of the 16 available digits that cancellation destroys. At what x does it pass 16?

Predict

You sum the series for e−20 directly, 1−20+2022!−⋯, in double precision. What happens?

Name it

Summing a series in code

Two habits make a series loop fast and correct:

  1. Build each term from the last. For ex, the next term is the previous one times xn. Computing xn and n! separately is slower and overflows for large n.
  2. Stop on a relative tolerance. Stop when the term is smaller than about 10−16 times the running total. A fixed absolute tolerance is wrong for big answers and for small ones.
def exp_series(x, tol=1e-16):
    total, term, n = 1.0, 1.0, 0
    while abs(term) > tol * abs(total):
        n += 1
        term *= x / n
        total += term
    return total, n

Cancellation

Floating-point numbers carry about 16 significant digits. Subtracting nearly equal numbers keeps their absolute error but makes the result small, so its relative error grows. In an alternating series, if the largest term is 10k times the final answer, about k digits are lost. For e−x with large x that's catastrophic; for the series of sin⁡x with large x it's just as bad.

Range reduction

Libraries avoid large arguments altogether:

  • sin and cos: subtract the nearest multiple of 2π (and use symmetries to get within ±π4). Python's math.remainder(x, 2*math.pi) gives a value in [−π,π].
  • exp: compute e−x as 1/ex, and for large x write x=kln⁡2+r with |r|≤ln⁡22, so ex=2ker and the series only ever sees a small r.

After range reduction a dozen terms suffice, and a fixed polynomial with tuned coefficients replaces the open-ended loop. That's what the C library actually ships.

Worked example

About how many digits are lost computing e−10 from its alternating series?

Show the solution
  1. Find the largest term. It's near n=10: 101010!=2756
  2. Compare it with the answer. The answer is e−10=4.54×10−5, so the ratio is 6.1×107.
  3. Count the digits lost. log10⁡(6.1×107)=7.8 so about 7.8 digits are lost, leaving about 8 good ones.
  4. Try x=20. There the loss is 16.3 digits, which is all of them.

Answer about 7.8 digits are lost, leaving about 8 good ones.

Worked example

How many terms does exp_series take at x=1, x=5 and x=20?

Show the solution
  1. Run the loop. It gives 18, 33 and 67.
  2. See why large arguments are slow. The loop must pass the peak term near n=x and then wait for the factorial to bring the terms down by 16 orders of magnitude, so large arguments are slow as well as risky.
  3. Reduce the range. With range reduction to |r|≤0.35, 14 terms always suffice.

Answer 18 terms at x=1, 33 at x=5 and 67 at x=20.

Check

Write exp_series(x) returning (total, n): the sum of the series for ex, built term by term, stopping when the term is below 1e-16 times the total; n is the number of terms added after the first. The test uses x = 2.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write sin_series(x) that first reduces x into [−π,π] with math.remainder(x, 2*math.pi), then sums x−x33!+⋯ until the term is below 1e-17 in size. The tests try large arguments.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

About how many decimal digits are lost computing e−20 from its alternating series? (Largest term divided by the answer, as a power of ten.)

Check

What does math.remainder(x, 2*math.pi) return for x = 13?

Check

Why does a math library reduce the argument before summing a series?

Check

Write ln1p(x, tol=1e-12) returning (value, terms) for ln⁡(1+x)=x−x22+x33−⋯, stopping when a term's size is below tol. Compare the term counts at x = 0.1 and 0.9.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Explain why

Why does summing the series for e−20 directly give a wrong answer, while 1/e20 is accurate?

Practice

Keep practicing

6 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.