Search code examples
algorithmmathcalculusmathematical-expressions

Recursively differentiating basic expression


If I have an expression, such as x * x * x, stored in a data structure like: mult(var x, mult(var x, var x))

And I want to implement a function to recursively differentiate the equation (so to 3 * x * x or x*x + (x + x)*x etc, no simplification required), any suggestions how to being this?


Solution

  • You would find a matching differentiation rule and apply it. For example in this case we have the rule (where A and B stand for whole subexpressions)

    diff(mult(A, B)) -> add(mult(diff(A),B), mult(A, diff(B)))
    

    The left hand side of this rule matches the formula when we set

    A = var x
    B = mult(var x, var x)
    

    So we can apply this rule to the formula and get

    diff(mult(var x, mult(var x, var x))) ->
      add(mult(diff(var x),mult(var x, var x)), mult(var x, diff(mult(var x, var x))))
    

    Now do the same recursively for the remaining diff operations.

    The other other rule you will need here is:

    diff(var x) -> 1