How many strips are enough

Without the exact answer you can still tell when a numerical result is good enough, by comparing it with the result for half as many strips.

What to build

Double the number of trapezoid strips until two successive estimates agree within a tolerance.

Requirements

  • Compute the trapezoid estimate T(n) for n = 1, 2, 4, 8, …
  • Stop at the first n (after the first) where |T(n) − T(n/2)| is below tol.
  • Print that n and T(n). If n would exceed 4096, print limit instead.

Input

Line 1: 1 to 6 whole-number coefficients, highest power first. Line 2: a, b (decimals, a less than b) and tol (a decimal).

Output

Two lines n N and value V with V to 6 decimal places, or the single word limit.

Constraints

The coefficients and the limits are between -10 and 10. The tolerance is between 0.0000001 and 1.

Example

Input:

1 0 0
0 3 0.01

Output:

n 64
value 9.001099

Why it works

The trapezoid error falls about four times each time n doubles, so once two successive estimates agree to tol, the true error is about a third of that gap. The comparison needs no exact answer, which is why this loop is used in real integration code.

Examples

Example 1 · Input
1 0 0
0 3 0.01
Expected output
n 64
value 9.001099
Example 2 · Input
1 0
0 2 0.5
Expected output
n 2
value 2.000000

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

Hints

Hint 1

Start with n = 1 and double it each round: 1, 2, 4, 8, …

Hint 2

Stop when the new trapezoid estimate and the previous one differ by less than tol (compare each round with the one before it).

Hint 3

Give up and print `limit` if n would pass 4096. Print n and the estimate with `:.6f`.

Solution

Show one correct solution (try it yourself first)
coeffs = [float(c) for c in input().split()]
a, b, tol = input().split()
a, b, tol = float(a), float(b), float(tol)

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

def trapezoid(n):
    w = (b - a) / n
    total = (f(a) + f(b)) / 2
    for i in range(1, n):
        total += f(a + i * w)
    return total * w

n = 1
previous = trapezoid(1)
while True:
    n *= 2
    if n > 4096:
        print("limit")
        break
    current = trapezoid(n)
    if abs(current - previous) < tol:
        print("n", n)
        print(f"value {current + 0.0:.6f}")
        break
    previous = current

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

Lesson: Numerical integration →