Scan a range for the lowest value

When you cannot solve f′(x) = 0, you can still scan a range and keep the best point seen.

What to build

Find the lowest value of a polynomial on an interval by checking evenly spaced points.

Requirements

  • Read the coefficients, the interval [a, b] and the number of strips n.
  • Check the n + 1 points a, a + step, …, b where step = (b − a) ÷ n.
  • Print the x with the lowest f(x) and that value, each to 4 decimal places.

Input

Line 1: 2 to 6 whole-number coefficients, highest power first. Line 2: whole numbers a, b and n with a less than b and n from 1 to 1000.

Output

Two lines: x X and f F, each to 4 decimal places.

Constraints

Coefficients, a and b are between -20 and 20. The tests have no ties.

Example

Input:

1 -4 3
0 5 10

Output:

x 2.0000
f -1.0000

Why it works

On a fine grid the best grid point is close to the true minimum, and the error shrinks as n grows. Gradient-free scanning is slow but never needs a derivative, so it is a useful check for smarter methods.

Examples

Example 1 · Input
1 -4 3
0 5 10
Expected output
x 2.0000
f -1.0000
Example 2 · Input
1 0 0
-3 4 7
Expected output
x 0.0000
f 0.0000

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

Hints

Hint 1

The grid points are a + i × (b − a) / n for i from 0 to n.

Hint 2

Keep the smallest f seen so far; if two points tie, keep the first.

Hint 3

Evaluate f with Horner's rule and print with `:.4f`.

Solution

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

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

best_x, best_f = a, f(a)
for i in range(1, n + 1):
    x = a + i * (b - a) / n
    if f(x) < best_f:
        best_x, best_f = x, f(x)
print(f"x {best_x + 0.0:.4f}")
print(f"f {best_f + 0.0:.4f}")

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

Lesson: Maxima, minima and gradient descent →