Implement the product rule for computing derivatives. Given two functions f and g represented as callable functions, compute the derivative of their product: d/dx [f(x) g(x)] = f'(x) g(x) + f(x) * g'(x).
import numpy as np
def numerical_derivative(f, x: float, h: float = 1e-7) -> float:
return (f(x + h) - f(x - h)) / (2 * h)
def product_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)
derivative = f_prime * g_val + f_val * g_prime
return {
"derivative": derivative,
"f(x)": f_val,
"g(x)": g_val,
"f'(x)": f_prime,
"g'(x)": g_prime,
}
def product_rule_array(f_vals: np.ndarray, g_vals: np.ndarray,
f_derivs: np.ndarray, g_derivs: np.ndarray) -> np.ndarray:
return f_derivs * g_vals + f_vals * g_derivs