Check a gradient numerically

A hand-derived gradient is easy to get wrong. A central-difference check catches the mistake before gradient descent runs on it.

What to build

Print the exact gradient and a numeric estimate of it for a quadratic surface.

Requirements

  • Read the coefficients a, b, c, d, e and the point (x, y).
  • Compute the exact gradient and the central-difference gradient with h = 0.00001.
  • Print both with 4 decimal places.

Input

Line 1: five numbers a, b, c, d, e. Line 2: two numbers x and y. All can be decimals.

Output

Two lines: exact GX GY and numeric GX GY, with 4 decimal places each.

Constraints

All numbers are between -10 and 10.

Example

Input:

1 0 3 0 0
1 2

Output:

exact 2.0000 12.0000
numeric 2.0000 12.0000

Why it works

For a quadratic the central difference is exact apart from tiny rounding noise, so the two lines must agree. For other functions they agree up to the small error of the method, and a mismatch reveals a mistake in the formula.

Examples

Example 1 · Input
1 0 3 0 0
1 2
Expected output
exact 2.0000 12.0000
numeric 2.0000 12.0000
Example 2 · Input
1 1 1 1 1
0 0
Expected output
exact 1.0000 1.0000
numeric 1.0000 1.0000

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

Hints

Hint 1

f(x, y) = a·x² + b·x·y + c·y² + d·x + e·y. Its exact partials are 2a·x + b·y + d and b·x + 2c·y + e.

Hint 2

For the numeric partial in x, change only x: (f(x + h, y) − f(x − h, y)) ÷ (2h) with h = 0.00001.

Hint 3

Print with `round(v, 4) + 0.0` first so tiny negative noise never shows as -0.0000.

Solution

Show one correct solution (try it yourself first)
a, b, c, d, e = [float(v) for v in input().split()]
x, y = [float(v) for v in input().split()]

def f(px, py):
    return a * px * px + b * px * py + c * py * py + d * px + e * py

def r(v):
    return f"{round(v, 4) + 0.0:.4f}"

h = 0.00001
gx = 2 * a * x + b * y + d
gy = b * x + 2 * c * y + e
nx = (f(x + h, y) - f(x - h, y)) / (2 * h)
ny = (f(x, y + h) - f(x, y - h)) / (2 * h)
print("exact", r(gx), r(gy))
print("numeric", r(nx), r(ny))

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

Lesson: Gradients and gradient descent →