On Wed, Apr 4, 2012 at 12:53 PM, vweber <[email protected]> wrote: > Dear All > > I would need to take the derivative of very long functions (and at the > end call fcode()), so > eg: > > f1(x)=... > f2(x)=... > f3(x)=...+f2(x) > f(x)=f1(x)*f3(x) > > and I target df/dx. The sympy code would look like > > x = symbols('x') > f1=... > f2=... > f3=...+f2 > f=f1*f3 > fcode(diff(f,x)) > > and this will produce a long expression. > > Then is it possible to tell sympy to keep some of the intermediate > function? eg > > df/dx = df1/dx * f3 + ... > > and not explicitly substitute f3 with its expression, so that at the > end my fortran code would look like
Not the way you are (apparently) doing it now, because there is no way for SymPy to know that you have the variables f1, f2, ... set, and built f3 from f1 and f2 (see http://docs.sympy.org/0.7.1/gotchas.html#variables-assignment-does-not-create-a-relation-between-expressions). Rather, you want to assign each thing symbolically, and use subs() to put them in there when you want them. I'm not sure how to get this exactly using fcode(), as that's a module I haven't really used. But if you define Function('f1'), and so on and define f as Function('f1')(x)*Function('f3')(x), you'll get In [230]: f = Function('f1')(x)*Function('f3')(x) In [231]: print f.diff(x) f1(x)*Derivative(f3(x), x) + f3(x)*Derivative(f1(x), x) You can later substitute for f1(x) and f3(x) (you may have to call .doit() to make the derivatives evaluate): In [233]: print f.subs({Function('f1')(x): exp(x), Function('f3')(x): sin(x)}) exp(x)*sin(x) (by the way, I thought you actually did have to call .doit(), but apparently you don't. Did that change?) Aaron Meurer > > f1= > f2=... > f3=...+f2 > df1dx=... > df2dx=... > df3dx=...+df2dx > dfdx=df1dx*f3+f1*df3dx > > Many thanks > > V > > -- > You received this message because you are subscribed to the Google Groups > "sympy" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group at > http://groups.google.com/group/sympy?hl=en. > -- You received this message because you are subscribed to the Google Groups "sympy" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/sympy?hl=en.
