A power of a polynomial is a function inside a function, which is the job of the chain rule.
What to build
For f(x) = g(x)ⁿ, print the derivative from the chain rule and a numeric estimate to compare with it.
Requirements
- g is a polynomial given by its coefficients, highest power first, and n is a whole number from 2 to 6.
- Compute the chain-rule value n · g(x)ⁿ⁻¹ · g′(x).
- Compute the central-difference estimate of f′(x) with h = 0.0001.
- Print both with 3 decimal places.
Input
Line 1: the whole-number coefficients of g (2 to 5 numbers). Line 2: n. Line 3: a whole number x.
Output
Two lines: chain C and numeric N, each to 3 decimal places.
Constraints
The coefficients and x are between -5 and 5. The values stay below one million.
Example
Input:
1 0
3
2
Output:
chain 12.000
numeric 12.000
Why it works
The outer function is u ↦ uⁿ with derivative n·uⁿ⁻¹, and the inner function is g. The chain rule multiplies the outer derivative at g(x) by g′(x). The numeric value is an independent check.
Examples
1 0 3 2
chain 12.000 numeric 12.000
1 1 2 1
chain 4.000 numeric 4.000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
If f(x) = g(x)ⁿ, then f′(x) = n · g(x)ⁿ⁻¹ · g′(x).
Hint 2
Evaluate g and g′ at x with the power rule, then combine.
Hint 3
For the numeric check use h = 0.0001 and print it with `:.3f`; add 0.0 to avoid printing -0.000.
Solution
Show one correct solution (try it yourself first)
coeffs = [int(c) for c in input().split()]
n = int(input())
x = int(input())
deg = len(coeffs) - 1
def g(t):
total = 0
for c in coeffs:
total = total * t + c
return total
def dg(t):
total = 0
for i, c in enumerate(coeffs[:-1]):
total = total * t + c * (deg - i)
return total
chain = n * g(x) ** (n - 1) * dg(x)
h = 0.0001
numeric = ((g(x + h)) ** n - (g(x - h)) ** n) / (2 * h)
print(f"chain {chain + 0.0:.3f}")
print(f"numeric {numeric + 0.0:.3f}")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step