Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define a "derivation" function in sympy

I am trying to make a derivation Function in sympy (I am using sympy version 1.4), but I am not sure how. In particular, I am trying to define a general function (that could just take sympy variables, not functions for now) that has the following properties:

d(f+g)=d(f)+d(g)
d(f*g)=f*d(g)+d(f)*g

I have tried reading the sympy documentation on defining Functions but I am not sure how to define a Function class that has the above properties for any two symbols.

For some background/context, I know how to make derivations in Mathematica; I would just type

d[f_+g_]:=d[f]+d[g]
d[f_ g_]:=f d[g] + d[f] g
like image 882
physics_researcher Avatar asked Dec 03 '25 00:12

physics_researcher


1 Answers

You can write your own rule. The following might get you started:

def d(e, func):
  """
  >>> from sympy import x, y
  >>> from sympy import Function
  >>> D = Function('D')
  >>> d(x + y, D)
  D(x) + D(y)
  """
  if e.is_Add:
    return Add(*[d(a, func) for a in e.args])
  elif e.is_Mul:
    return Add(*[Mul(*(e.args[:i]+(d(e.args[i],func),)+e.args[i+1:]))
        for i in range(len(e.args))])
  else:
    return func(e)

Or you could try this with a class:

class d(Function):
  @classmethod
  def eval(cls, e):
    if e.is_Add:
        return Add(*[d(a) for a in e.args])
    elif e.is_Mul:
        return Add(*[Mul(*(e.args[:i]+(d(e.args[i]),)+e.args[i+1:]))
           for i in range(len(e.args))])
    else:
        return d(e, evaluate=False)

See also, linapp.

like image 92
smichr Avatar answered Dec 04 '25 14:12

smichr