0
$\begingroup$

How to evaluate df function in the following code sample?

    f[x_,y_]:=Sqrt[x^4-4x^2 y^2]
    df[x_,y_,dx_,dy_]:=Sqrt[(D[f[x,y],x]dx)^2+(D[f[x,y],y] dy)^2]
    df[1,2,0.2,0.3]

General::ivar: 1 is not a valid variable. >> General::ivar: 2 is not a valid variable. >>

$\endgroup$
3
  • 2
    $\begingroup$ := says to evaluate the right hand side later when the function is called. Next df[1,2,0.2,0.3] sets x equal to 1 and y equal to 2. Next evaluate the right hand side doing D[f[1,2],1] and you don't know how to differentiate with respect to 1. Same for 2. If you change the := to = in your definition of the df function and you clear all definitions or restart Mathematica then the right hand side is evaluated before df[1,2..2,.3] and the error message goes away. But you must be very careful with this to be certain that the answer is correct. $\endgroup$
    – Bill
    Commented May 15, 2019 at 3:55
  • $\begingroup$ It works for this sample, but it does not twork for more complicated code which contains many functions. $\endgroup$ Commented May 15, 2019 at 4:21
  • $\begingroup$ Please read this tutorial on how to differentiate := and =. It will help you in other contexts too. $\endgroup$
    – Roman
    Commented May 15, 2019 at 7:50

1 Answer 1

1
$\begingroup$

Use Derivative instead of D in your definitions:

df[x_,y_,dx_,dy_] = Sqrt[(Derivative[1,0][f][x,y] dx)^2+(Derivative[0,1][f][x,y] dy)^2];

Then:

df[1, 2, .2, .3]
0. + 0.95219 I
$\endgroup$
3
  • $\begingroup$ I suppose that df[x_,y_,dx_,dy_]=Sqrt[(D[f[x,y],x]dx)^2+(D[f[x,y],y] dy)^2] would work $\endgroup$ Commented May 15, 2019 at 10:01
  • $\begingroup$ Yes, the same @ClaudeLeibovici $\endgroup$ Commented May 16, 2019 at 8:44
  • $\begingroup$ many thanks for you @Carl Woll $\endgroup$ Commented May 17, 2019 at 21:33

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