Loading...
Loading...
You are given a polynomial f(x, y, z) of three variables, written as a string formula. The string is one or more terms joined by " + ". Each term is an integer, or an integer followed by " * " and then one or more of the letters x, y and z joined by " * ". That integer is the coefficient of the term and is never 0. A negative coefficient carries its minus sign inside its own term, so "3 * x * x + -2 * y + 5" is a valid formula. The value of a term is its coefficient times the product of its letters, each letter replaced by the value of the matching variable, so 3 * x * x * y at (2, 5, 0) is 60. The value of f at a point is the sum of the values of its terms.
The partial derivative of f with respect to x treats y and z as constants.
Implement the class PolynomialAutograd:
PolynomialAutograd(formula) creates an object for the polynomial written in formula.evaluate(x, y, z) returns f(x, y, z).gradient(x, y, z) returns a list of three integers: the partial derivatives of f with respect to x, y and z, in that order, at the point (x, y, z).discreteGradient(x, y, z, delta) returns a list of three numbers, one per variable in the order x, y, z. The entry for x is (f(x + delta, y, z) - f(x - delta, y, z)) / (2 * delta). The entry for y uses y + delta and y - delta with x and z unchanged, and the entry for z does the same for z.You can assume every value of f and of each partial derivative at a point used fits in a 32-bit integer. Answers from discreteGradient are accepted within an absolute or relative error of 10^-5.
Input: operations = ["PolynomialAutograd","evaluate","gradient","discreteGradient"], arguments = [["2 * x * x + 3 * y"],[1,2,3],[1,2,3],[1,2,3,1]]
Output: [null,8,[4,3,0],[4.0,3.0,0.0]]
Explanation: The value at `(1, 2, 3)` is `2 * 1 + 3 * 2 = 8`. The partial derivatives are `4 * x = 4`, `3` and `0`, and with `delta = 1` the discrete entries are `4`, `3` and `0` as well.
Input: operations = ["PolynomialAutograd","evaluate","gradient","discreteGradient"], arguments = [["7"],[-10,-10,-10],[0,0,0],[3,-4,5,2.5]]
Output: [null,7,[0,0,0],[0.0,0.0,0.0]]
Explanation: `f` is the constant `7`, so every value is `7` and every derivative, discrete or not, is `0`.
Input: operations = ["PolynomialAutograd","evaluate","gradient","discreteGradient"], arguments = [["1 * x * x * x + -2 * y"],[2,3,0],[2,3,0],[2,3,0,0.5]]
Output: [null,2,[12,-2,0],[12.25,-2.0,0.0]]
Explanation: The value at `(2, 3, 0)` is `8 - 6 = 2`. The partial derivatives are `3 * x * x = 12`, `-2` and `0`, while the discrete entry for `x` with `delta = 0.5` is `12.25`.
formula.length ≤200formula ≤6x, y, z ≤10delta ≤4f and of each partial derivative at a point used fits in a 32-bit integer.