16

I want to use a function's derivative in an other function. How should this be done in Maxima?

E.g:

f(x) := 2*x^4;
g(x) := diff(f(x),x)-8;

Now g(x) yields 8x^3-8 as expected, but g(0) gives an error, since diff(f(0),0) doesn't make sense. But then how should I properly define g?

4 Answers 4

20

Note that quote-quote is only understood when the code is parsed. That's OK if you only work in the interpreter but if you put stuff into scripts, it is possible to have unintended effects.

Another way to do this. It works the same in the interpreter and in a script.

define (g(x), diff (f(x), x) - 8);

See 'define'.

13

Michael's answer is good, but it does the differentiation everytime g(x) is called. (Also, normally you see it wrapped in a block statement to ensure that y is properly localized).

There is a way to force the RHS to evaluate at the time of definition and with the general x.
The syntax is

(%i1) f(x) := 2*x^4;
                                            4
(%o1)                            f(x) := 2 x
(%i2) g(x) := ''(diff(f(x), x) - 8);
                                          3
(%o2)                          g(x) := 8 x  - 8
(%i3) g(0);
(%o3)                                 - 8

Compare with the block construct:

(%i4) h(x) := block([y], subst([y = x], diff(f(y), y) - 8));
(%o4)        h(x) := block([y], subst([y = x], diff(f(y), y) - 8))
(%i5) h(0);
(%o5)                                 - 8

Notice (%o4) which shows that the RHS is unevaluated.

Ref: http://www.math.utexas.edu/pipermail/maxima/2007/004706.html

2
  • What makes g(x) := ''(diff(f(x), x) - 8); work, but doesn't h(x) := ''diff(f(x), x) - 8; ? In h the diff doesn't get evaluated.
    – shinjin
    Commented Dec 28, 2011 at 6:46
  • 2
    @shinjin: In order for the := operator to evaluate the RHS, the whole right hand side has to be wrapped with ''. I don't think that it parses the RHS to look for quoting until it is called. Also note that instead of the g(x) := ''(...) you could use the equivalent define(g(x), ...).
    – Simon
    Commented Jan 8, 2012 at 2:08
4

Not sure if this is the simplest answer, but it seems to do the right thing for me

(%i) g(x) := subst([y = x], diff(f(y), y) - 8);

(%i) g(x);
         8 x^3 - 8
(%i) g(0);
         -8
(%i) g(1);
         0
0

g(X) := at(diff(f(x),x)-8,x=X);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.