| 
     
      
      
      From: Robert D. <rob...@gm...> - 2024-04-25 05:43:40
      
     
   | 
On Wed, Apr 24, 2024 at 4:04 PM Oliver Ruebenacker via Maxima-discuss <
max...@li...> wrote:
> (%i3) g(x) := diff(f(x), x);
> (%o3)                        g(x) := diff(f(x), x)
> (%i4) g(0);
>
> diff: second argument must be a variable; found 0
Oliver, thanks for your interest in Maxima. The key here is that when a
function is defined by ":=", the function body is only evaluated at the
time the function is called, so when you call g(0), 0 is supplied for x,
and then diff(f(0), 0) causes trouble.
There are a couple of ways to ensure the derivative is calculated first and
then evaluated at x = 0. I think the more general way is to say
g(x) := at (diff (f(u), u), u = x);
That works equally well when f has already been defined when g is called,
and when f is undefined.
(%i2) g(x) := at (diff (f(u), u), u = x) $
(%i3) g(0);
                                  │
                         d        │
(%o3)                    ── (f(u))│
                         du       │
                                  │u = 0
(%i4) f(x) := x^2 + 3*x + 7 $
(%i5) g(0);
(%o5)                           3
Here 'at' is essentially a postponed substitution; '? at' at the input
prompt says more about it.
Two other approaches which work if f is already defined when the function g
is defined. 'define' evaluates the body, while ':=' does not. However, one
can subvert the lack of evaluation via the quote-quote operator (two single
quotes), which interpolates the value of its argument into another
expression.
(%i6) define (h(x), diff (f(x), x));
(%o6)                    h(x) := 2 x + 3
(%i7) h(0);
(%o7)                           3
(%i8) r(x) := ''(diff (f(x), x));
(%o8)                    r(x) := 2 x + 3
(%i9) r(0);
(%o9)                           3
The drawback of quote-quote is that it can really only be used at the input
prompt, because the interpolation happens at the time the expression is
read by the input parser.
Hope this helps,
Robert
 |