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?

shinjin
  • 2,858
  • 5
  • 29
  • 44

4 Answers4

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'.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
Robert Dodier
  • 16,905
  • 2
  • 31
  • 48
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

Simon
  • 14,631
  • 4
  • 41
  • 101
  • 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 Dec 28 '11 at 06: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 Jan 08 '12 at 02: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
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
0

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

Name
  • 339
  • 2
  • 18