Mathematica Asked by Sami on July 19, 2021
Consider this toy example:
myDerivative[f_, x_] := D[f, {x, 2}]
This defines a function myDerivative
that takes in a function f
and a variable x
and takes the second derivative of f
, i.e. it returns $f”$. This works as expected:
myDerivative[x^2, x]
2
However, consider a slightly different version:
myDerivative2[f_, x_] := D[f[x^2], {x, 2}]
The difference here is that before differentiation, the function f
is composed with x^2
. This particular composition here is irrelevant, it’s just to highlight that I have to somehow evaluate the function f
with my function, I can’t just leave as f
like before. This no longer works:
myDerivative2[x^2, x]
2[x^2] + 2 x Derivative[1][(2 x)][x^2] + 2 Derivative[1][(x^2)][x^2] + 2 x (Derivative[1][(2 x)][x^2] + 2 x ((x^2)^[Prime][Prime])[x^2])
It does, however, work if I supply a pure function, or just a head:
myDerivative2[#^2 &, x]
myDerivative2[Sin, x]
12 x^2 2 Cos[x^2] - 4 x^2 Sin[x^2]
How can I define myDerivative2
such that myDerivative[x^2, x]
works as expected, without resorting to inputting a pure function? Google surprisingly didn’t provide an answer to this (maybe I don’t know the right terms), all that I could find used pure functions like #^2&
or Sin
(just the head).
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP