1
$\begingroup$

I want to create a table with numerical values of a function derivative by using the following code:

f[x_, a_] := f[x, a] = Tanh[a (1 - Cos[x])];
g[x_, a_] := g[x, a] = D[f[x, a], x];
pderivative = Table[{x, Evaluate[g[x, 5]]}, {x, - π,  π, 2 π/500.}]

When I look at the result, it's not what I expect. Any trick to fix this? enter image description here

$\endgroup$
  • $\begingroup$ g = D[f[x, a], x]; pderivative = Table[{x, g /. a -> 5}, {x, -\[Pi], \[Pi], 2 \[Pi]/500.}] $\endgroup$ – Alex Trounev Nov 5 '18 at 10:48
  • 2
    $\begingroup$ 1. As mentioned by Henrik in this comment, memoization for functions with real arguments is usually rather pointless as the chances that exactly the same pops up somewhere else are rather low. 2. Don't abuse SetDelayed(:=). Related: mathematica.stackexchange.com/a/181586/1871 $\endgroup$ – xzczd Nov 5 '18 at 11:20
2
$\begingroup$

Method I

Define your g by Derivative instead of D:

g[x_, a_] := g[x, a] = Derivative[1, 0][f][x, a];

Note that Evaluate in pderivative is not a necessity.


Method II

Alternatively it also works in this way:

g[x_, a_] = D[f[x, a], x]

FYI, please check this link concerning the difference between Set (=) and SetDelayed (:=).

$\endgroup$
  • $\begingroup$ Many thanks! Is this due to two variables? $\endgroup$ – Bob Lin Nov 5 '18 at 11:28
  • $\begingroup$ @BobLin No, see my update. $\endgroup$ – Αλέξανδρος Ζεγγ Nov 5 '18 at 11:53
  • $\begingroup$ Why you take the derivative with respect to $a$? $\endgroup$ – Bob Lin Nov 5 '18 at 11:56
  • $\begingroup$ @BobLin Oh, sorry, just a typo; Corrected. $\endgroup$ – Αλέξανδρος Ζεγγ Nov 5 '18 at 11:58

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.