Here is an approach that follows @Szabolcs' suggestion in comments, i.e of plotting the derivative of the function to extract the values, then reporting those values back to a plot of the original function:
Clear[f]
f[x_?NumericQ] := Sin[x]
pts = Cases[
Normal@
Plot[
D[f[t], t] /. t -> x, {x, -5, 5},
MeshFunctions -> {#2 &}, Mesh -> {{-0.5}}
], p_Point :> First[p], All];
tangents = Function[{x}, f[#1] + #2 (x - #1) & @@@ pts];
Plot[
{f[x], Style[tangents[x], GrayLevel[0.5], Dashed]},
{x, -5, 5}, PlotRange -> 1.2,
Epilog -> {
PointSize[Large], Red,
Point[pts /. {x_Real, y_Real} :> {x, f[x]}]
},
ImageSize -> Large
]
I have defined the function in question as something that only evaluates when given numeric input to show that this should work with reasonable functions more complex than the simple Sin[x]
as well.
An alternative way to find those points is to use the NDSolve
machinery and WhenEvent
:
Reap[
NDSolve[
{D[y[x], x] == f'[x], y[0] == f[0], WhenEvent[y'[x] == -0.5, Sow[x]]},
y, {x, -5, 5}
]
][[2, 1]]
(* Out: {-2.0944, -4.18879, 2.0944, 4.18879} *)
Plot[
f[x], {x, -5, 5},
Epilog -> {
PointSize[Large], Red,
Point[{#1, f[#1]} & /@ ptsNDSolve]
}
]
y
coordinate but also thex
coordinate. Then we can use an explicit form of the derivative function, as Brett did. $\endgroup$