1 hour ago · Writing · 0 comments

Suppose you run across the power series for the exponential function and decide to code it up. Good idea: you’ll probably learn something, though maybe not what you expect. Maybe you decide a tolerance of 10−12 is good enough, and so you sum the terms until the next term to add is below the tolerance. from math import factorial, exp def naive_exp(x): tolerance = 1e-12 s = 0 n = 0 while True: delta = x**n / factorial(n) s += delta if abs(delta) < tolerance: return s n += 1 You want to try your program out, so you compute e by calling the function at 1. If you compare this to calling exp(1) you find that you got all the digits correct. Now you try computing exp(-20). Calling naive_exp(-20) gives 5.47893091802112e-10 but calling exp(-20) gives 2.061153622438558e-09 Don’t brush things like this as flukes or compiler bugs [1]. This is your golden opportunity to learn something. Maybe you add a print statement to see the intermediate values of the sum stored in the variable s. If you do,…

No comments yet. Log in to reply on the Fediverse. Comments will appear here.