If I define
f[x_?NumericQ] := (Sow[x]; SawtoothWave[x])
D[f[x], x] /. x -> 1.1
(* 5.29432 *)
numeric differentiation fails, despite the function being smooth and well-defined in a region around 1.1.
We can see the values of x
at which f
is evaluated
Reap[D[f[x], x] /. x -> 1.1]
(* {5.29432, {{1.1, 1.15263, 1.20526, 1.25789, 1.31053, 1.36316, 1.41579,
1.46842, 1.52105, 1.04737, 0.994737, 0.942105, 0.889474, 0.836842,
0.784211, 0.731579, 0.678947}}} *)
Mathematica provides ND
for numerical differentiation, which behaves sensibly
Needs["NumericalCalculus`"]
Reap[ND[f[x], x, 1.1, Scale -> 0.01]]
(* {1., {{1.1, 1.11, 1.105, 1.1025, 1.10125, 1.10063, 1.10031, 1.10016}}} *)
The documentation for D
does not provide obvious clues on what is to be expected with numeric arguments.
The sensible advice is not to use D
with numeric functions. However, it may not always be obvious to the user that D
will be applied to an expression.
Related question Derivative of mod gives unacceptable results
D[f[x],x]
gets turned intoDerivative[1][f][x]
(f'
), so this is really a question of howDerivative
behaves for numerical functions. You can investigate what's happening with:f[x_?NumericQ] := (Echo[{x, SawtoothWave[x]}]; SawtoothWave[x]); D[f[x], x] /. x -> 1.1
. It seems to naively sample some points with distance O(1), and then generate a result. $\endgroup$SawtoothWave'[1.1]
returns1
$\endgroup$Derivative
, which, as I recall, is slightly different fromND
. It could be discussed as a side-issue in a Q&A about something else, but for whatever reason, I can't locate it... $\endgroup$