Defining derivative functions.



[edA-qa mort-ora-y , Sun, 02 Jan 2005 15:49:41 +0100]:
> I need a way to define a function and its derivative as functions.
> That is, I want to accomplish what one might expect the following
> would do:
> 
> f(x) := q*x^2 + r;
> df(x) := diff( f('x), 'x );

One way if it is acceptable to differentiate only once (so that a
redefinition of f(x) won't be detected):

    (%i1) f(x) := q*x^2 + r;
    
                                              2
    (%o1)                          f(x) := q x  + r
    (%i2) df(x) := ''(block([x], diff(f(x), x)));
    
    (%o2)                           df(x) := 2 q x
    (%i3) df(1);
    
    (%o3)                                 2 q
    
(The block is a safeguard against a possible value of x:


    (%i4) x: 3;
    
    (%o4)                                  3
    (%i5) df(x) := ''(block([x], diff(f(x), x)));
    
    (%o5)                           df(x) := 2 q x

)


Or, if you want to differentiate in every call, try

    (%i6) df2(x) := subst(x, 'x, block([x], diff(f(x), x)));
    
    (%o6)          df2(x) := SUBST(x, 'x, BLOCK([x], DIFF(f(x), x)))
    (%i7) df2(1);
    
    (%o7)                                 2 q
    (%i8) f(x) := 4*x^2;
    
                                                2
    (%o8)                            f(x) := 4 x
    (%i9) df2(1);
    
    (%o9)                                  8


There may be simpler ways of doing this, though.

Regards,

Albert.