Taylor in one variable: polynomials, remainders and power series
A review of Taylor's theorem with its three remainder forms (Peano, Lagrange and integral), and power series with their radius of convergence. Smooth and analytic functions are distinguished, and complex singularities are shown to determine the radius. The lab builds exp from scratch as a mathematical library does: argument reduction plus a polynomial with an error bound.
After this lesson you can
- State and prove Taylor's theorem with Lagrange and integral remainders.
- Bound the error of a Taylor approximation and choose the minimum degree for a given tolerance.
- Calculate convergence radii using Cauchy–Hadamard and explain them through singularities in the complex plane.
- Operate with complex numbers in polar form and derive Euler's formula from the exponential power series.
- Distinguish C^∞ functions from analytic functions using the e^{-1/x²} counterexample.
- Implement an elementary function with argument reduction, Horner evaluation and a guaranteed error bound.
Before you start
Motivation: every local model is a Taylor polynomial
Almost everything calculated in ML, optimization and numerical analysis relies on one idea: near a point, a complicated function resembles a polynomial. You have already used it without naming it.
- Linearization is first-order Taylor. The derivative is the unique number with . Each gradient descent step relies on that linear model, and its largest reasonable size is determined by what the model ignores: the second-order term.
- Second-order optimization is second-order Taylor. Newton’s method minimizes instead of , and its step, , is the vertex of that parabola (its minimum when ). In several variables, becomes the Hessian.
- Finite differences are truncated Taylor expansions. Approximating by incurs an error exactly equal to the first-order Taylor remainder divided by , and checking a hand-coded gradient with the Taylor test verifies that the error decreases like .
- Your library’s elementary functions are polynomials.
np.exp,np.log1portorch.tanhreduce the argument to a small interval and evaluate a polynomial (or quotient of polynomials) whose degree was chosen using an error bound. At the end of the lesson you will buildexpthis way, with at most one ulp of error at every point you test. - Itô’s lemma and the delta-gamma approximation in quantitative finance are second-order Taylor expansions; in Itô’s, moreover, a term discarded in ordinary calculus, , cannot be discarded (you will see this in Itô’s lemma).
This lesson is a specialist-level review. It answers three questions left open by the high-school version: how much error is made (remainders and their bounds), how far the approximation extends when the whole series is summed (the radius of convergence), and why that radius is sometimes much smaller than the real graph suggests (the answer is in the complex plane, which we will construct along the way).
Intuition: increasing the order does not always help
The Taylor polynomial of order of at is the polynomial that shares with its value and first derivatives at . For at , every derivative is 1 and
The natural question is whether as , and for which . The following figure starts with , a function with nothing unusual on the real line: positive, bounded and infinitely differentiable.
Three different behaviors, all with infinitely differentiable functions:
- Convergence on the entire line (, ). The farther from the center, the higher the order needed, but raising it always suffices.
- Convergence on a symmetric interval around the center (, ). Inside, the error decreases geometrically with ; outside, it grows geometrically. The interval’s half-width, the radius, depends on the center in a way the real graph does not explain: for at it is .
- Convergence to the wrong function ( at 0). Every derivative at 0 is zero, so and the series converges everywhere, but to 0, not to .
The rest of the lesson names and proves each phenomenon: the Taylor remainder explains the first, power series the second, the difference between smooth and analytic functions the third, and the complex plane explains why the second radius has its value.
The Taylor polynomial
The factor makes the derivatives agree: differentiating times gives , and every different power vanishes at after differentiating it times (lower powers disappear and higher powers retain a factor ). Thus for , and is the unique polynomial of degree with that property, because a polynomial of degree is determined by its derivatives at a point.
But the property that matters is that is the best polynomial approximation to near , in the precise sense of Landau notation.
Proof
Existence, by induction on . For this is the definition of derivative: . Suppose the result holds for and let be as in the statement. The remainder is differentiable near and its derivative is , because differentiating the Taylor polynomial of gives that of with one lower order. The function satisfies the assumptions with , so : given there is with if . Since , the mean value theorem gives, for , a between and with
Uniqueness. If and satisfy the property, is a polynomial of degree with . If , write it as with . Then , whereas . Contradiction.
∎Uniqueness is the most useful computational tool in this topic: any polynomial of degree approximating with error is the Taylor polynomial, however it was obtained. No differentiation is needed.
The remainder: Peano, Lagrange and integral
The Peano remainder says the error is small compared with as , but gives no number: it does not let us guarantee, for example, that calculates with 16 correct digits at . For that we need explicit expressions for the Taylor remainder. Two are classical: the integral form, obtained by integration by parts and an exact identity, and Lagrange’s form, deduced from it (or directly, with weaker assumptions, from the mean value theorem).
For this is the fundamental theorem of calculus, . To pass to , integrate by parts with and , but choose the antiderivative instead of , so that it vanishes at endpoint :
That is the whole trick: each integration by parts extracts one more polynomial term and raises the degree of the kernel by one. The full induction is the first guided exercise in the lesson.
The integral remainder is exact, not a bound. The other forms follow from it. Since does not change sign between and and is continuous, the mean value theorem for integrals gives a between and with
Proof
Fix and define, for between and , and . On differentiating , the sum telescopes:
Also , and . Cauchy’s version of the mean value theorem gives between and with , that is,
Since , divide by to obtain the formula. This proof does not need to be continuous or even integrable.
∎The three forms answer different questions. Peano gives the order of magnitude as and is used to calculate limits and expansions. Lagrange provides a computable bound if a derivative can be bounded, and determines the degree of a polynomial in a library. The integral is an exact identity and generalizes to several variables (as you will see in multivariable Taylor), operators and Itô’s formula.
The Lagrange bound has two drawbacks worth seeing before using it. First, must be bounded over the entire interval, not at the center. Second, it is a sufficient condition: it may be much greater than the true error, or even fail to tend to zero when the error does.
The minimum-degree reading summarizes the strategy behind every elementary-function implementation. To put the absolute error bound for below (half the ulp of 1 in float64, of the order of rounding when is near 1), Lagrange requires degree 13 at , 18 at , 24 at and 33 at , and at it would be useless. But that is unnecessary: since and multiplication by is exact in floating point, it suffices to calculate for . Reducing the interval is much cheaper than raising the degree, because the error depends on : dividing by 2 gains bits at once.
Power series and radius of convergence
If is we can sum all the terms and ask where the result converges. This leads to studying power series in their own right, without reference to any .
Proof
Apply the root test (from the series convergence lesson) to :
If it is less than 1, the series of absolute values converges. If it exceeds 1, infinitely many have , so the general term does not tend to zero and the series diverges.
∎The convergence set is therefore an interval centered at , perhaps including one or both endpoints. When the limit exists, the ratio test gives the same result: .
| Series | At | At | |
|---|---|---|---|
| 1 | diverges | diverges | |
| 1 | diverges (harmonic) | converges (Leibniz), to | |
| 1 | converges | converges | |
| 0 |
What makes power series so convenient is that, inside their interval, they can be treated as polynomials.
The radius staying unchanged is easy: because , and dividing by does not change convergence. The delicate part is that the derivative of the sum equals the sum of derivatives, an interchange of limits. It is justified by uniform convergence on every with , and we will prove it in the lesson on interchanging limits. Applying the theorem times and evaluating at gives . Term-by-term integration also preserves the radius; for example, this gives from .
Analytic versus smooth functions
By the preceding theorem, an analytic function is and the series representing it near is necessarily its Taylor series at . The question is the converse: is every analytic? No, and the counterexample is the function in the first figure.
What fails is that the remainder does not tend to zero. This is the general criterion: if and only if , and Lagrange gives a convenient sufficient condition. If for every and every in , then at every with (and the segment from to inside )
For the derivatives near 0 grow faster than any , and the bound breaks down.
Analytic functions are rigid: what they do on one piece determines what they do everywhere.
Proof
Let . It is nonempty (it contains the subinterval). It is closed in because it is the intersection of the sets , closed because are continuous. And it is open: if , the Taylor series of at is zero and agrees with it near , so vanishes in a neighborhood of , as do all its derivatives. An interval cannot be split into two nonempty disjoint open sets, hence .
∎The practical consequence is bump functions. The function for and elsewhere is (the argument is the same as for ) and has compact support . By the identity principle it cannot be analytic: it vanishes on without being identically zero. Such functions exist only because smoothness is much more flexible than analyticity, and they underlie mollifiers for regularizing functions and partitions of unity. The flexibility is extreme: a theorem of Borel guarantees that for any sequence there is a with . With the Taylor series is , which has radius 0.
Complex numbers and Euler’s formula
To understand the second behavior in the first figure, the finite radius of , we must leave the real line. We need complex numbers, and while we are at it, we construct them with just what the rest of the course needs.
In polar form, multiplication becomes geometric. If , expanding the product and using the sum formulas for sine and cosine,
Multiplying by scales by and rotates by . Multiplying by rotates by , which is why rotates by . This is the same geometry as the complex eigenvalues of a real matrix, which rotates and scales on an invariant plane.
The modulus satisfies and , and with distance is with the Euclidean distance, complete. Therefore everything seen about series carries over unchanged: an absolutely convergent complex series converges, and the root test and Cauchy–Hadamard theorem hold word for word. Only the geometry of the convergence set changes: is no longer an interval, but a disk. Hence the name “radius”.
The most important series is the exponential. Since , the series
converges absolutely for every . Evaluated at a purely imaginary number , the powers of cycle through , and the even terms are real and the odd ones imaginary:
Separating the series into even and odd terms is valid because it converges absolutely (as absolute convergence justifies: the two subseries converge and sum to the total), and each parenthesis is the Taylor series of and , converging to those functions by Lagrange. This is Euler’s formula, , derived rather than defined.
Two consequences close the circle. The first is for all , proved by multiplying the two series (the Cauchy product of two absolutely convergent series converges to the product) and grouping using the binomial theorem. With it, , polar form becomes and the multiplication rule is simply : the trigonometric sum formulas are property read in real and imaginary parts. The second is the identity , the figure’s initial state.
Why has radius 1
Now we can explain the first figure. For real , , so
Expand around a real point with , as a geometric series:
Taking the imaginary part, the Taylor coefficients of at are . In polar form, with and , so
Therefore , and equality is attained in the limit superior because and cannot both be small: from , if , then . The radius is exactly
the distance from to the points , where has its poles. On the real line there is no obstacle; the obstacle is at , and the real convergence interval is the intersection with the real axis of a disk that cannot contain .
The phenomenon is general, although its proof belongs to complex analysis and we only state it here: if is complex differentiable on the disk , its Taylor series at converges to throughout that disk. Therefore the radius of convergence is the distance from the center to the nearest complex singularity (the nearest point at which can no longer be extended in this way). And it cannot be larger when blows up at that singularity: the sum of a power series is continuous, and thus bounded, on every closed disk contained in its convergence disk, so if it contained the singularity, the sum (which agrees with near and, by the identity principle in , throughout the common region) would remain bounded near a point where .
With this rule we can read radii without calculating a single coefficient:
- has poles where , at . At 0, radius .
- The sigmoid has poles where , at . At 0, radius ; at , .
- , whose series defines the Bernoulli numbers, has a removable singularity at 0 and poles at , : radius .
- has at , where , a branch point: there is no way to define it continuously in any neighborhood of . Radius at .
For people working with neural networks, the lesson is concrete: a Taylor polynomial of or at 0 does not work outside or , however many terms are taken. If you need to approximate an activation by a polynomial on a wider interval, the Taylor expansion is the wrong tool and minimax approximation or Chebyshev approximation on that interval is the right one.
Applications
Finite-difference truncation error
Taylor’s theorem with Lagrange remainder gives the error of any finite-difference formula. For , , so
The error is . For the central difference, with , subtract the order-2 expansions of and : the even terms cancel and remains. By the intermediate value theorem, the average of the two values of is for some , and
But truncation is not the only error. Each evaluation of has roundoff error of order , with , and dividing by amplifies that error: the total forward-difference error is of order , minimized when . For the central difference, .
import numpy as np
import matplotlib.pyplot as plt
f, df = np.sin, np.cos
x0 = 1.0
eps = np.finfo(float).eps
hs = 10.0 ** -np.arange(1, 15.01, 0.25)
err_del = np.abs((f(x0 + hs) - f(x0)) / hs - df(x0))
err_cen = np.abs((f(x0 + hs) - f(x0 - hs)) / (2 * hs) - df(x0))
i, j = err_del.argmin(), err_cen.argmin()
print(f"hacia delante: mejor h = {hs[i]:.1e}, error {err_del[i]:.1e} (sqrt(eps) = {np.sqrt(eps):.1e})")
print(f"centrada: mejor h = {hs[j]:.1e}, error {err_cen[j]:.1e} (eps^(1/3) = {np.cbrt(eps):.1e})")
print(f"con h = 1e-2: error centrado {err_cen[np.argmin(np.abs(hs - 1e-2))]:.4e}, "
f"Taylor predice h^2 |cos 1| / 6 = {1e-4 * np.cos(1) / 6:.4e}")
plt.loglog(hs, err_del, "o-", ms=3, label="hacia delante")
plt.loglog(hs, err_cen, "o-", ms=3, label="centrada")
plt.loglog(hs, hs / 2 * abs(np.sin(x0)), "--", color="gray", label="truncamiento h |f''| / 2")
plt.loglog(hs, hs**2 / 6 * abs(np.cos(x0)), ":", color="gray", label="truncamiento h² |f'''| / 6")
plt.loglog(hs, eps / hs, "-.", color="gray", label="redondeo ε / h")
plt.xlabel("h"); plt.ylabel("error en f'(1)"); plt.ylim(1e-14, 1); plt.legend(); plt.show()The graph is V-shaped: truncation dominates on the right, with slope 1 or 2 depending on the formula, and roundoff on the left, with slope . The forward difference minimum is near , with about eight correct digits; the central one reaches twelve with . And Taylor’s prediction for agrees with measured error to four digits. This is what the Taylor test does for gradients: if your gradient is correctly programmed, the error of falls like ; if it falls like , there is a bug.
The tanh approximation to GELU
The GELU activation is , with the standard normal cumulative distribution function. Many implementations instead use
proposed in the original paper (Hendrycks and Gimpel, 2016). Where do the constants come from? Taylor. On one hand, , integrating the density’s series term by term. On the other, with and ,
Equating the coefficient of gives . Equating that of , , gives . The constant used, , is close but different: the cell checks that it reduces maximum error on the entire line, what matters in a network, while Taylor’s is optimal only near 0.
import numpy as np
from scipy.special import erf
x = np.linspace(-6, 6, 120001)
gelu = 0.5 * x * (1 + erf(x / np.sqrt(2)))
c = np.sqrt(2 / np.pi)
b_taylor = 2 / (3 * np.pi) - 1 / 6
for nombre, b in [("Taylor", b_taylor), ("implementaciones", 0.044715)]:
aprox = 0.5 * x * (1 + np.tanh(c * (x + b * x**3)))
err = np.abs(aprox - gelu)
cerca = np.abs(x) < 0.5
print(f"b = {b:.6f} ({nombre:16s}): error máx en |x| < 0.5: {err[cerca].max():.1e} en [-6, 6]: {err.max():.1e}")Near 0 the Taylor constant wins because it matches one more term; over the entire line the fitted one wins. This tension recurs throughout the lesson: Taylor is the best local approximation, not the best on an interval.
Implementation from scratch: exp with guaranteed error
We will write exp(x) for every float64 as a math library does: argument reduction, a Taylor polynomial evaluated by Horner’s rule, and a degree chosen using the Lagrange bound. First, the two small pieces.
Horner. Evaluating by computing each power separately costs on the order of multiplications (or if powers are reused) and accumulates errors in each power. Horner’s rule rewrites the polynomial as
which is exactly multiplications and additions. Moreover, with coefficients decreasing like those of the exponential, roundoff errors in the inner stages are multiplied by small and barely matter.
The degree. For and , Lagrange gives , and we seek the smallest with that bound below .
import math
import numpy as np
def lagrange_bound(M, r, n):
"""Cota de Lagrange del resto de orden n en [-r, r] si |f^(n+1)| <= M allí."""
return M * r ** (n + 1) / math.factorial(n + 1)
def choose_degree(M, r, tol):
n = 0
while lagrange_bound(M, r, n) >= tol:
n += 1
return n
def horner(c, x):
"""c[0] + c[1] x + ... + c[n] x^n con n productos y n sumas."""
y = np.zeros_like(x) + c[-1]
for ck in c[-2::-1]:
y = y * x + ck
return y
R = math.log(2) / 2
for r in [R, 1.0, 2.0, 4.0, 8.0]:
print(f"exp en [-{r:.4f}, {r:.4f}]: grado mínimo {choose_degree(math.exp(r), r, 2.0**-53)}")
N = choose_degree(math.sqrt(2), R, 2.0**-53)
C = np.array([1 / math.factorial(k) for k in range(N + 1)])
print(f"\ngrado elegido: {N}; cota {lagrange_bound(math.sqrt(2), R, N):.2e} < 2^-53 = {2.0**-53:.2e}")
rng = np.random.default_rng(0)
r = rng.uniform(-R, R, 1_000_000)
ref = np.exp(r)
por_potencias = sum(C[k] * r**k for k in range(N + 1))
por_horner = horner(C, r)
ulp = np.spacing(ref)
print(f"error máx término a término: {np.max(np.abs(por_potencias - ref) / ulp):.0f} ulp")
print(f"error máx con Horner: {np.max(np.abs(por_horner - ref) / ulp):.0f} ulp")Thirteen is the degree in the numerical exercise at the end. Note that the measured error with Horner is at most one ulp while term-by-term evaluation reaches several: the Lagrange bound controls truncation, but rounding depends on how evaluation is performed.
Argument reduction. Write with and . Then , and multiplication by only changes the float’s exponent (np.ldexp), without error. Care is needed only in computing : is not representable and subtracting would cancel digits. Cody and Waite’s trick splits into a high part with low bits zero, so is exact for the encountered, and a low part that corrects it.
import mpmath
LN2_HI = 6.93147180369123816490e-01 # ln 2 con los bits bajos de la mantisa a cero
LN2_LO = 1.90821492927058770002e-10 # ln 2 - LN2_HI
print("LN2_HI + LN2_LO == ln 2:", LN2_HI + LN2_LO == math.log(2), " LN2_HI =", float.hex(LN2_HI))
def my_exp(x):
x = np.asarray(x, dtype=float)
k = np.rint(x / math.log(2)) # x = k ln 2 + r, |r| <= ln2 / 2
r = (x - k * LN2_HI) - k * LN2_LO # k * LN2_HI es exacto
return np.ldexp(horner(C, r), k.astype(np.int64)) # e^x = 2^k e^r
def ulps(y, ref):
return np.abs(y - ref) / np.spacing(np.abs(ref))
x = rng.uniform(-700, 700, 2_000_000)
u = ulps(my_exp(x), np.exp(x))
print(f"{x.size:,} puntos en [-700, 700]: error máx {u.max():.0f} ulp; idénticos a np.exp: {np.mean(u == 0):.1%}")
# ¿quién tiene razón cuando difieren? valor exacto con 200 bits, redondeado a float64
mpmath.mp.prec = 200
xs = x[:2000]
exacto = np.array([float(mpmath.exp(mpmath.mpf(float(v)))) for v in xs])
print(f"frente al valor correctamente redondeado: my_exp {ulps(my_exp(xs), exacto).max():.0f} ulp, "
f"np.exp {ulps(np.exp(xs), exacto).max():.0f} ulp")
# sin reducción de argumento: grado 59 alrededor de 0
c60 = np.array([1 / math.factorial(k) for k in range(60)])
for v in [1.0, 10.0, 20.0, -20.0]:
ingenua = float(horner(c60, np.array(v)))
print(f"sin reducir, x = {v:6.1f}: error relativo {abs(ingenua - math.exp(v)) / math.exp(v):.1e}")A few lines suffice to match np.exp within one ulp at two million points, and where they differ neither is always correctly rounded. Without reduction, however, the same method fails: at truncation is already noticeable with 60 terms, and at the result is garbage, because the series sums terms of size with alternating signs to obtain , catastrophic cancellation. Reduction avoids both problems at once.
ln(1 + x) for small x
The same analysis explains why np.log1p exists. For , 1 + x rounds to 1 and np.log(1 + x) returns 0 instead of . For somewhat larger , is computed with relative error up to , an absolute error of the same size in the logarithm, and since , the relative error is of order : with twelve digits are lost. The solution is never to form when is small. For fourth-order Taylor suffices. If the series alternates with decreasing terms and the error is bounded by the first omitted term, ; if all terms have the same sign and the tail is bounded by . In both cases absolute error is below , and relative error below . For the rest, Kahan’s trick with compensates rounding of (Goldberg, 1991, theorem 4).
def my_log1p(x):
x = np.asarray(x, dtype=float)
u = 1 + x
d = u - 1 # lo que realmente se sumó a 1 (exacto si u >= 1/2)
with np.errstate(divide="ignore", invalid="ignore"):
kahan = np.where(d == 0, x, np.log(u) * (x / d))
taylor = x - x**2 / 2 + x**3 / 3 - x**4 / 4 # error < |x|^5 / 5 si |x| < 1e-4
return np.where(np.abs(x) < 1e-4, taylor, kahan)
print(" x error rel. log(1 + x) error rel. my_log1p")
for v in [1e-1, 1e-3, 1e-5, 1e-8, 1e-12, 1e-15, 1e-18]:
ref = np.log1p(v)
print(f" {v:7.0e} {abs(np.log(1 + v) - ref) / ref:18.1e} {abs(my_log1p(v) - ref) / ref:18.1e}")
X = np.concatenate([10 ** rng.uniform(-18, 0, 500_000), -(10 ** rng.uniform(-18, np.log10(0.75), 500_000))])
print(f"\n1e6 puntos en (-0.75, 1): my_log1p a {ulps(my_log1p(X), np.log1p(X)).max():.0f} ulp de np.log1p como mucho")With libraries
sympy.series computes exact expansions, from which the radius can be estimated from the coefficients and compared with the distance to singularities found by sympy.solveset. The root converges slowly, because if the factor takes time to approach 1; the ratio of two consecutive nonzero coefficients, , eliminates and converges much faster.
import sympy as sp
x = sp.symbols("x")
print(sp.series(sp.tan(x), x, 0, 8))
print(sp.series(x / (sp.exp(x) - 1), x, 0, 8), "\n")
casos = {
"1/(1 + x^2)": (1 / (1 + x**2), 1 + x**2, 1.0),
"tanh x": (sp.tanh(x), sp.cosh(x), float(sp.pi / 2)),
"x/(e^x - 1)": (x / (sp.exp(x) - 1), sp.exp(x) - 1, float(2 * sp.pi)),
}
N = 24
for nombre, (f, den, esperado) in casos.items():
s = sp.series(f, x, 0, N).removeO()
c = np.array([float(s.coeff(x, k)) for k in range(N)])
k = np.flatnonzero(c)
k = k[k > 0]
raiz = abs(c[k[-1]]) ** (-1 / k[-1])
k1, k2 = k[-2], k[-1]
cociente = (abs(c[k1]) / abs(c[k2])) ** (1 / (k2 - k1))
print(f"{nombre:12s} raíz: {raiz:.4f} cociente: {cociente:.6f} distancia a la singularidad: {esperado:.6f}")
print(f"{'':12s} ceros del denominador: {sp.solveset(den, x, domain=sp.S.Complexes)}")In all three cases the ratio gives the radius to five or six digits and agrees with the distance to the closest zero of the denominator. In the zero does not count: the quotient has limit 1 there and the singularity is removable, so the first actual singularity is at .
For evaluating and manipulating polynomials, numpy.polynomial provides Horner (polyval) and operations in several bases. The final cell compares the Taylor polynomial of at with the Chebyshev interpolant of the same degree. Taylor’s is exact at the center and worsens toward the endpoints; Chebyshev’s distributes error across the interval and, at the same degree, is 60 to over 500 times more accurate at degrees 6 to 9 (it reaches machine precision at degree 10, one or two fewer than Taylor). That is why real libraries do not use pure Taylor but minimax polynomials (you will see this in Chebyshev series); Taylor gives the starting point, approximate degree and bound guaranteeing the result.
from numpy.polynomial import Polynomial, Chebyshev
import matplotlib.pyplot as plt
t = np.linspace(-R, R, 20001)
print(" grado Taylor (error rel.) Chebyshev (error rel.)")
for d in range(6, 12):
tay = Polynomial([1 / math.factorial(k) for k in range(d + 1)])
che = Chebyshev.interpolate(np.exp, d, domain=[-R, R])
et = np.max(np.abs(tay(t) - np.exp(t)) / np.exp(t))
ec = np.max(np.abs(che(t) - np.exp(t)) / np.exp(t))
print(f" {d:3d} {et:16.1e} {ec:18.1e}")
print("\nPolynomial evalúa con Horner:", np.allclose(Polynomial(C)(t), horner(C, t), rtol=0, atol=1e-15))
d = 7
plt.plot(t, (Polynomial([1 / math.factorial(k) for k in range(d + 1)])(t) - np.exp(t)) / np.exp(t), label=f"Taylor, grado {d}")
plt.plot(t, (Chebyshev.interpolate(np.exp, d, domain=[-R, R])(t) - np.exp(t)) / np.exp(t), label=f"Chebyshev, grado {d}")
plt.xlabel("r"); plt.ylabel("error relativo"); plt.legend(); plt.show()Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. How is the case , proved?
Step 1 of 4. What form do the derivatives of take for ?
taylor_eval(coeffs, x0, x) to evaluate by Horner's rule (it must accept a number or NumPy array in x), and choose_degree(deriv_bound, r, tol) to return the smallest such that the Lagrange bound deriv_bound(n + 1) * r**(n + 1) / (n + 1)! is strictly less than tol. Here deriv_bound(m) bounds on the interval . The tests use exp, sin and cos.import math
import numpy as np
def taylor_eval(coeffs, x0, x):
"""Evalúa sum_k coeffs[k] * (x - x0)**k por Horner. x puede ser un número o un array."""
# tu código
return 0.0 * np.asarray(x, dtype=float)
def choose_degree(deriv_bound, r, tol):
"""Menor n con deriv_bound(n + 1) * r**(n + 1) / (n + 1)! < tol."""
# tu código
return 0Summary
- is the unique polynomial of degree with . By uniqueness, expansions are computed algebraically (substitution, product, quotient) without differentiating.
- Integral remainder , by parts; from it, Lagrange , whose bound requires bounding throughout the interval.
- A power series converges on with (Cauchy–Hadamard), can be differentiated term by term with the same radius, and is the Taylor series of its sum.
- Analytic implies , but not conversely: and bump functions are smooth and not analytic. Analytic functions obey the identity principle.
- In , multiplying by scales by and rotates by , and follows by separating the exponential series into even and odd terms.
- has radius at due to its poles at ; the sigmoid, at 0; , .
- An elementary function is implemented by reducing the argument to a small interval () and evaluating by Horner a polynomial whose degree is fixed by the Lagrange bound: reducing the interval is much more effective than increasing the degree.