Estimate the integral of a polynomial from a to b with the midpoint rule, and compare it with the exact value.
Input
Line 1: the polynomial's whole-number coefficients, highest power first (1 to 10 numbers). Line 2: a, b and n, where a and b are decimals with a less than b, and n is the number of strips (1 to 1000).
Output
Two lines: midpoint M (the sum of n midpoint rectangles) and exact E (from an antiderivative), each to 6 decimal places.
Examples
Example 1 · Input
1 0 0 0 3 3
Expected output
midpoint 8.750000 exact 9.000000
Example 2 · Input
1 0 0 2 4
Expected output
midpoint 2.000000 exact 2.000000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Strip i (from 0) has its midpoint at a + (i + 0.5) × width.
Hint 2
An antiderivative of c·xᵏ is c·xᵏ⁺¹ ÷ (k + 1).
Hint 3
The exact area is F(b) − F(a).
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)
deg = len(coeffs) - 1
def f(x):
return sum(c * x ** (deg - i) for i, c in enumerate(coeffs))
def F(x):
return sum(c * x ** (deg - i + 1) / (deg - i + 1) for i, c in enumerate(coeffs))
width = (b - a) / n
total = sum(f(a + (i + 0.5) * width) for i in range(n)) * width
print(f"midpoint {total:.6f}")
print(f"exact {F(b) - F(a):.6f}")