A Taylor series builds a function from powers of x. A few terms of the series for eˣ are already very accurate.
What to build
Approximate eˣ with the first n terms of its Taylor series and report the error.
Requirements
- Read x and the number of terms n.
- Add the terms 1, x, x²/2!, … for n terms, building each term from the previous one.
- Print the approximation, the exact
math.exp(x)and the absolute error.
Input
One line: x (a decimal) and n (a whole number from 1 to 40).
Output
Three lines: approx A, exact E and error D, each to 6 decimal places.
Constraints
x is between -5 and 5.
Example
Input:
1 5
Output:
approx 2.708333
exact 2.718282
error 0.009948
Why it works
Each term of the series is the previous term times x ÷ k, so no large factorials are needed. Because k! grows faster than xᵏ, the terms eventually shrink and the partial sums converge to eˣ for every x.
Examples
1 5
approx 2.708333 exact 2.718282 error 0.009948
1 10
approx 2.718282 exact 2.718282 error 0.000000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Start with term = 1 and total = 0. For k = 0 to n - 1: total += term, then term = term * x / (k + 1).
Hint 2
Get the exact value from `math.exp`, then print the error as the absolute difference.
Hint 3
Print all three numbers with `:.6f`.
Solution
Show one correct solution (try it yourself first)
from math import exp
x, n = input().split()
x, n = float(x), int(n)
term, total = 1.0, 0.0
for k in range(n):
total += term
term = term * x / (k + 1)
exact = exp(x)
print(f"approx {total + 0.0:.6f}")
print(f"exact {round(exact, 12):.6f}")
print(f"error {abs(exact - total):.6f}")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step