The derivative gives a straight line that approximates a curve near a point, and following that line finds roots very fast.
What to build
Use Newton's method to find a root of a polynomial from a starting guess.
Requirements
- Repeat x ← x − f(x) ÷ f′(x), at most 50 times.
- Stop early when the change in x is below 1e-12.
- If f′(x) is 0 at any point, print
flatand stop. - Otherwise print the final x to 6 decimal places.
Input
Line 1: 2 to 6 whole-number coefficients, highest power first. Line 2: the starting guess x0, a decimal.
Output
root X with X to 6 decimal places, or flat.
Constraints
Coefficients are between -20 and 20. The tests only use starting points where the method converges or the slope is exactly 0.
Example
Input:
1 0 -2
1
Output:
root 1.414214
Why it works
Near x the curve looks like its tangent line. The tangent reaches zero at x − f(x) ÷ f′(x), which is usually much closer to the root. Each step roughly doubles the number of correct digits.
Examples
1 0 -2 1
root 1.414214
1 0 -2 -1
root -1.414214
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The tangent at x crosses zero at x − f(x) ÷ f′(x). Repeat from that new point.
Hint 2
Evaluate f with Horner's rule and f′ from the power rule. If f′(x) is 0, print `flat` and stop.
Hint 3
Stop after 50 steps or earlier when the step is smaller than 1e-12. Print with `:.6f`.
Solution
Show one correct solution (try it yourself first)
coeffs = [int(c) for c in input().split()]
x = float(input())
n = len(coeffs) - 1
def f(t):
total = 0.0
for c in coeffs:
total = total * t + c
return total
def df(t):
total = 0.0
for i, c in enumerate(coeffs[:-1]):
total = total * t + c * (n - i)
return total
for _ in range(50):
d = df(x)
if d == 0:
print("flat")
break
new = x - f(x) / d
done = abs(new - x) < 1e-12
x = new
if done:
break
else:
pass
if d != 0:
print(f"root {x:.6f}")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step