Area between two curves

The area between two curves is an integral of their difference, and crossings mean the sign must be handled.

What to build

Find the area between two polynomial curves over an interval with the midpoint rule.

Requirements

  • Read the coefficients of f and of g (highest power first) and the interval [a, b].
  • Use exactly 2000 strips and the midpoint rule on |f(x) − g(x)|.
  • Print the area with 3 decimal places.

Input

Line 1: coefficients of f (1 to 5 whole numbers). Line 2: coefficients of g (1 to 5 whole numbers). Line 3: a and b, whole numbers with a less than b.

Output

One line: area A, with A to 3 decimal places.

Constraints

The coefficients and the limits are between -5 and 5.

Example

Input:

1 0
1 0 0
0 1

Output:

area 0.167

Why it works

The area between curves is the integral of the upper curve minus the lower curve. When they cross, the difference changes sign, so we take its absolute value to count every piece as positive area. With 2000 strips the midpoint error is far below the 3 printed decimals.

Examples

Example 1 · Input
1 0
1 0 0
0 1
Expected output
area 0.167
Example 2 · Input
2
0
0 3
Expected output
area 6.000

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

The height of the region at x is the absolute difference |f(x) − g(x)|, because the curves can cross.

Hint 2

Use 2000 midpoint strips: width = (b - a) / 2000 and height at a + (i + 0.5) * width.

Hint 3

Evaluate both polynomials with Horner's rule and print with `:.3f`.

Solution

Show one correct solution (try it yourself first)
f = [int(c) for c in input().split()]
g = [int(c) for c in input().split()]
a, b = [int(v) for v in input().split()]

def ev(coeffs, x):
    total = 0.0
    for c in coeffs:
        total = total * x + c
    return total

n = 2000
width = (b - a) / n
area = 0.0
for i in range(n):
    x = a + (i + 0.5) * width
    area += abs(ev(f, x) - ev(g, x)) * width
print(f"area {area:.3f}")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Integrals: area under a curve →