The trapezoid rule joins the curve's heights at the strip ends with straight lines.
What to build
Estimate the integral of a polynomial with the trapezoid rule.
Requirements
- Read the coefficients, the interval [a, b] and n.
- Use n equal strips of width w = (b − a) ÷ n.
- Count the two end heights by half and the middle heights fully, then multiply by w.
- Print the result with 6 decimal places.
Input
Line 1: 1 to 6 whole-number coefficients, highest power first. Line 2: a, b and n, with a and b decimals, a less than b, and n from 1 to 1000.
Output
One line: trapezoid T, with T to 6 decimal places.
Constraints
The coefficients and the limits are between -10 and 10.
Example
Input:
1 0 0
0 3 3
Output:
trapezoid 9.500000
Why it works
Each strip becomes a trapezoid with area (left height + right height) ÷ 2 × w. Adding them all counts each middle height twice (once for each neighbour) and each end height once, which gives the half-weights at the ends.
Examples
1 0 0 0 3 3
trapezoid 9.500000
2 1 0 1 1
trapezoid 2.000000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The sum is (f(a) / 2 + f(a + w) + … + f(b - w) + f(b) / 2) * w, where w = (b - a) / n.
Hint 2
Loop i from 1 to n - 1 for the middle points.
Hint 3
Print with `:.6f`.
Solution
Show one correct solution (try it yourself first)
coeffs = [float(c) for c in input().split()]
a, b, n = input().split()
a, b, n = float(a), float(b), int(n)
def f(x):
total = 0.0
for c in coeffs:
total = total * x + c
return total
w = (b - a) / n
total = (f(a) + f(b)) / 2
for i in range(1, n):
total += f(a + i * w)
print(f"trapezoid {total * w + 0.0:.6f}")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step