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$
  • 1
    $\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 May 15 at 3:55
  • $\begingroup$ Thank you @Bill $\endgroup$ – Emad Raslan May 15 at 4:12
  • $\begingroup$ It works for this sample, but it does not twork for more complicated code which contains many functions. $\endgroup$ – Emad Raslan May 15 at 4:21
  • $\begingroup$ Please read this tutorial on how to differentiate := and =. It will help you in other contexts too. $\endgroup$ – Roman May 15 at 7:50
  • $\begingroup$ thank you @Roman $\endgroup$ – Emad Raslan May 16 at 8:42
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$
  • $\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$ – Claude Leibovici May 15 at 10:01
  • $\begingroup$ Yes, the same @ClaudeLeibovici $\endgroup$ – Emad Raslan May 16 at 8:44
  • $\begingroup$ many thanks for you @Carl Woll $\endgroup$ – Emad Raslan May 17 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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