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$
2
  • $\begingroup$ g = D[f[x, a], x]; pderivative = Table[{x, g /. a -> 5}, {x, -\[Pi], \[Pi], 2 \[Pi]/500.}] $\endgroup$ Nov 5, 2018 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, 2018 at 11:20

1 Answer 1

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$
4
  • $\begingroup$ Many thanks! Is this due to two variables? $\endgroup$
    – Bob Lin
    Nov 5, 2018 at 11:28
  • $\begingroup$ @BobLin No, see my update. $\endgroup$ Nov 5, 2018 at 11:53
  • $\begingroup$ Why you take the derivative with respect to $a$? $\endgroup$
    – Bob Lin
    Nov 5, 2018 at 11:56
  • $\begingroup$ @BobLin Oh, sorry, just a typo; Corrected. $\endgroup$ Nov 5, 2018 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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