Re: Derivatives of user-defined control-flow functions
- To: mathgroup at smc.vnet.net
- Subject: [mg51096] Re: Derivatives of user-defined control-flow functions
- From: ab_def at prontomail.com (Maxim)
- Date: Mon, 4 Oct 2004 06:18:17 -0400 (EDT)
- References: <cjoiel$al2$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
"Maxim A. Dubinnyi" <maxim at nmr.ru> wrote in message news:<cjoiel$al2$1 at smc.vnet.net>... > Can anyone correctly define derivatives of > user-defined control-flow functions? > > The derivative of build-in control function 'If' is evaluated as: > > In[]= D[If[f[x], g[x], h[x]], x] > Out[]= If[f[x],g'[x],h'[x]] > > Which is perfectly correct answer. I wish to introduce my own > control flow function MyIf and define it's derivatives with > properties identical to ones in build-in If function. > Usually derivatives are defined via properties of > symbol 'Derivative' by setting > > Derivative[order...][function_name]:= (derivative definition) > > but this method fails in case of control-flow expressions. > The problem origin is in the rule for derivatives of > composite functions: > > In[]= D[f[g[x]], x] > Out[]= f'[g[x]]g'[x] > > This rule should not be applied if 'f' is control-flow function such > as 'If', 'Which', etc, and it is really so for build-in control-flow > expressions. But how can I suppress this deepely build-in rule for > some user-defined symbols? > > I am experienced user of Mathematica, and I use widely symbolic > and functional programming in my applications, > but can't find any solution of this problem. > > Is it the task which can't be solved by means of Mathematica > symbolic programming language? > > > Maxim A. Dubinnyi You can add a definition for D: In[1]:= Clear[myIf] myIf /: D[myIf[a_, b_, c_], vars__] := myIf[a, D[b, vars], D[c, vars]] D[myIf[a[x, y], x^2, -x^2], {x, 2}] Out[3]= myIf[a[x, y], 2, -2] If you need the definitions for Derivative, you can look at how it is done for If and emulate it: In[4]:= Clear[myIf] myIf /: Derivative[1, 0, 0][myIf] = 0&; myIf /: Derivative[0, 1, 0][myIf] = myIf[#, 1, 0]&; myIf /: Derivative[0, 0, 1][myIf] = myIf[#, 0, 1]&; D[myIf[a[x, y], x^2, -x^2], {x, 2}] Out[8]= -2 myIf[a[x, y], 0, 1] + 2 myIf[a[x, y], 1, 0] (If you omit TagSet, then the definitions will be stored as SubValues for Derivative, which can be pretty confusing). Notice that while Mathematica's rule for the differentiation of If can be handy, it is, strictly speaking, not correct; for example: In[9]:= D[If[x == 0, 0, Sin[x]^2/x], x] Out[9]= If[x == 0, 0, (2*Sin[x]*Cos[x])/x - Sin[x]^2/x^2] while the correct value for the derivative at zero is 1. Maxim Rytin m.r at inbox.ru
- Follow-Ups:
- Re: Re: Derivatives of user-defined control-flow functions
- From: "Maxim A. Dubinnyi" <maxim@nmr.ru>
- Re: Re: Derivatives of user-defined control-flow functions