Two ways to estimate a slope differ in accuracy, and an exact formula lets you see by how much.
What to build
For a polynomial at a whole-number x, print the forward estimate, the central estimate and the exact derivative.
Requirements
- Read the coefficients (highest power first) and the point x.
- Use h = 0.01 for the forward estimate (f(x + h) − f(x)) ÷ h and the central estimate (f(x + h) − f(x − h)) ÷ (2h).
- Compute the exact derivative from the power rule.
- Print all three with 4 decimal places.
Input
Line 1: 2 to 6 whole-number coefficients, highest power first. Line 2: a whole number x.
Output
Three lines: forward F, central C, exact E, each to 4 decimal places.
Constraints
Coefficients and x are between -10 and 10.
Example
Input:
1 0 0
3
Output:
forward 6.0100
central 6.0000
exact 6.0000
Why it works
The forward error is about h × f″(x) ÷ 2, while the central error is about h² × f‴(x) ÷ 6, so the central estimate lands much closer to the exact derivative.
Examples
1 0 0 3
forward 6.0100 central 6.0000 exact 6.0000
1 0 0 0 2
forward 12.0601 central 12.0001 exact 12.0000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Evaluate the polynomial with Horner's rule: start at 0 and do total = total * x + c for each coefficient.
Hint 2
The exact derivative of c·xᵏ is c·k·xᵏ⁻¹. Build it from the coefficients without a library.
Hint 3
Use h = 0.01 for both estimates and print each result with `:.4f`.
Solution
Show one correct solution (try it yourself first)
coeffs = [int(c) for c in input().split()]
x = int(input())
def f(t):
total = 0.0
for c in coeffs:
total = total * t + c
return total
n = len(coeffs) - 1
exact = sum(c * (n - i) * x ** (n - i - 1) for i, c in enumerate(coeffs) if n - i > 0)
h = 0.01
forward = (f(x + h) - f(x)) / h
central = (f(x + h) - f(x - h)) / (2 * h)
print(f"forward {forward + 0.0:.4f}")
print(f"central {central + 0.0:.4f}")
print(f"exact {exact + 0.0:.4f}")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step