Simpson's rule fits a parabola to every pair of strips, which makes it exact for cubics.
What to build
Estimate an integral with Simpson's rule and show how far it is from the exact value.
Requirements
- Read the coefficients, the limits a and b, and an even n.
- Compute Simpson's estimate with n strips.
- Compute the exact integral from an antiderivative.
- Print the estimate, the exact value and the error (exact − estimate), each to 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 an even whole number from 2 to 1000.
Output
Three lines: simpson S, exact E and error D, each to 6 decimal places.
Constraints
The coefficients and the limits are between -10 and 10.
Example
Input:
1 0 0 0
0 1 2
Output:
simpson 0.250000
exact 0.250000
error 0.000000
Why it works
On each pair of strips Simpson's rule integrates the parabola through three points exactly. For a polynomial of degree 3 or less the parabola fits so well that the error is 0, and for higher degrees the error falls about sixteen times when n doubles.
Examples
1 0 0 0 0 1 2
simpson 0.250000 exact 0.250000 error 0.000000
1 0 0 0 0 0 1 2
simpson 0.208333 exact 0.200000 error -0.008333
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Simpson's weights are 1, 4, 2, 4, …, 2, 4, 1 times w ÷ 3, where w = (b - a) / n.
Hint 2
Odd i get weight 4 and even middle i get weight 2.
Hint 3
The exact value comes from the antiderivative term by term. Print the error as exact minus Simpson, 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)
deg = len(coeffs) - 1
def f(x):
total = 0.0
for c in coeffs:
total = total * x + c
return total
def F(x):
return sum(c * x ** (deg - i + 1) / (deg - i + 1) for i, c in enumerate(coeffs))
w = (b - a) / n
total = f(a) + f(b)
for i in range(1, n):
total += (4 if i % 2 == 1 else 2) * f(a + i * w)
simpson = total * w / 3
exact = F(b) - F(a)
print(f"simpson {simpson + 0.0:.6f}")
print(f"exact {exact + 0.0:.6f}")
print(f"error {round(exact - simpson, 6) + 0.0:.6f}")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step