1
$\begingroup$

I often find myself in use cases where I have to write something like this:

F1[x_] := Cos[x] + Sin[x]*x;
F2[x_] := Module[
  {genericX},
  D[F1[genericX], genericX] /. {genericX -> x}
  ]

And then I want to run something like this:

Table[F2[i], {i, 1, 100}]

But before, I might play around with the definition F1 until I'm sure it's the function I want to use. I assume that every iteration of the Table call is literally doing symbolic differentiation of F1 and then evaluating it. Is there any way to make this more efficient? Let's say at some point I know I want to evaluate the Table command for several iterations and obviously I know that F1 won't change during that execution. What's the best way to avoid the symbolic differentiation every iteration? The only option I know of would be to compute the symbolic derivative in an independent cell and then literally copy the code into a new function, but that's the kind of thing I want to avoid. Is there a more automated way to do it? Maybe function compilation is a reasonable thing to do?

$\endgroup$
  • 2
    $\begingroup$ Use F2[x_] = D[F1[x], x]. The differentiation is performed once, and F2[x] simply evaluates the expression produced by the differentiation. $\endgroup$ – bbgodfrey Jun 12 '18 at 4:32
1
$\begingroup$

This is what Derivative is for (this is mostly equivalent to @bbgodfrey's suggestion in the comments):

F3 = F1'

Cos[#1] #1 &

Note that the FullForm of F1' is Derivative[1][F1]. Then:

Trace[F3[1]]

{{F3,Cos[#1] #1&},(Cos[#1] #1&)[1],Cos[1] 1,Cos[1]}

Compare this with:

Trace[F2[1]] //InputForm

(*
{HoldForm[F2[1]], HoldForm[Module[{genericX$}, D[F1[genericX$], genericX$] /. {genericX$ -> 1}]], 
 {{{HoldForm[F1[genericX$9510]], HoldForm[Cos[genericX$9510] + Sin[genericX$9510]*genericX$9510], 
    {HoldForm[Sin[genericX$9510]*genericX$9510], HoldForm[genericX$9510*Sin[genericX$9510]]}, 
    HoldForm[Cos[genericX$9510] + genericX$9510*Sin[genericX$9510]]}, 
   HoldForm[D[Cos[genericX$9510] + genericX$9510*Sin[genericX$9510], genericX$9510]], HoldForm[genericX$9510*Cos[genericX$9510]]}, 
  {{HoldForm[genericX$9510 -> 1], HoldForm[genericX$9510 -> 1]}, HoldForm[{genericX$9510 -> 1}]}, 
  HoldForm[genericX$9510*Cos[genericX$9510] /. {genericX$9510 -> 1}], HoldForm[1*Cos[1]], HoldForm[Cos[1]]}, HoldForm[Cos[1]]}
*)
$\endgroup$

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.