← back

Quotient Rule for Derivatives

#312 · Calculus · Medium

⊣ Solve on deep-ml.com

Problem

Implement the quotient rule for derivatives. Given two functions f and g, compute the derivative of f(x)/g(x) = (f'(x)g(x) - f(x)g'(x)) / g(x)^2.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def numerical_derivative(f, x: float, h: float = 1e-7) -> float:
    return (f(x + h) - f(x - h)) / (2 * h)

def quotient_rule(f, g, x: float) -> dict:
    f_val = f(x)
    g_val = g(x)
    f_prime = numerical_derivative(f, x)
    g_prime = numerical_derivative(g, x)

    if abs(g_val) < 1e-12:
        raise ValueError("g(x) is zero; quotient is undefined.")

    derivative = (f_prime * g_val - f_val * g_prime) / (g_val ** 2)

    return {
        "derivative": derivative,
        "f(x)": f_val,
        "g(x)": g_val,
        "f'(x)": f_prime,
        "g'(x)": g_prime,
    }

Explanation

  1. The quotient rule states: (f/g)' = (f' g - f g') / g^2.
  2. Evaluate f(x), g(x), f'(x), and g'(x). Derivatives are computed numerically via central differences.
  3. Check that g(x) is not zero (the quotient would be undefined).
  4. Apply the formula to get the derivative of the quotient at point x.
  5. This is equivalent to applying the product rule to f(x) * (1/g(x)) but more direct.

Complexity

  • Time: O(1) for a single point (4 function evaluations)
  • Space: O(1)