A6 · Lesson 45 · Series in code
How a math library computes exp and sin
When you call math.exp(x), something has to turn 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 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 of the series for , on a log scale (each unit up is a factor of 10).
- The terms grow until , then fall. For the same terms appear with alternating signs, and they must cancel down to the tiny answer .
- The readout estimates how many of the 16 available digits that cancellation destroys. At what does it pass 16?
Predict
You sum the series for directly, , in double precision. What happens?
Every digit is wrong. The largest terms are about , and they have to cancel down to , sixteen orders of magnitude smaller. Each term carries a rounding error near of its size, about , as big as the answer itself. The fix is simple: compute , whose terms are all positive, and take .
Name it
Summing a series in code
Two habits make a series loop fast and correct:
- Build each term from the last. For , the next term is the previous one times . Computing and separately is slower and overflows for large .
- Stop on a relative tolerance. Stop when the term is smaller than about 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 times the final answer, about digits are lost. For with large that's catastrophic; for the series of with large it's just as bad.
Range reduction
Libraries avoid large arguments altogether:
- sin and cos: subtract the nearest multiple of (and use symmetries to get within ). Python's
math.remainder(x, 2*math.pi)gives a value in . - exp: compute as , and for large write with , so and the series only ever sees a small .
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 from its alternating series?
Show the solution
- Find the largest term. It's near :
- Compare it with the answer. The answer is , so the ratio is .
- Count the digits lost. so about 7.8 digits are lost, leaving about 8 good ones.
- Try . 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 , and ?
Show the solution
- Run the loop. It gives 18, 33 and 67.
- See why large arguments are slow. The loop must pass the peak term near 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.
- Reduce the range. With range reduction to , 14 terms always suffice.
Answer 18 terms at , 33 at and 67 at .
Check
Write exp_series(x) returning (total, n): the sum of the series for , 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 = 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 into with math.remainder(x, 2*math.pi), then sums 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 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 = 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 , stopping when a term's size is below tol. Compare the term counts at = 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 directly give a wrong answer, while is accurate?
The series for alternates, and its terms grow to about before shrinking. To land on the true value, , those huge terms must cancel almost perfectly. Each one carries a rounding error of about one part in of its size, around , which is as large as the answer, so the result is noise. The series for has only positive terms, so nothing cancels and every digit is good; dividing 1 by it keeps that accuracy.
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.