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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With