11
$\begingroup$

Say I have an expression (call it expr) involving a function, f[x]. I'd like to be able to evaluate that for a particular choice of f[x] without setting that choice for the whole session. I thought to do this using a replacement,

expr /. f[x_]->x^2

(where expr is some expression involving f[x] and I want to set f to x^2), but this doesn't work on derivatives, e.g., if expr contains f'[x] then it will stay as f'[x] rather than become 2x.

What's the best solution to this problem?

$\endgroup$
  • 1
    $\begingroup$ Check FullForm[f'[x]] to understand why, and figure out the appropriate replacement rule. $\endgroup$ – István Zachar Jan 10 '14 at 18:45
  • $\begingroup$ István - alright, I can see why it doesn't work, although I'm not sure how to construct a more general replacement rule. Still learning. Any hints? $\endgroup$ – Adam Jan 11 '14 at 0:08
  • $\begingroup$ You can replace f by a pure function if you want things like derivatives to work. f->Function[x, x^2] $\endgroup$ – Rojo Jan 11 '14 at 0:41
  • $\begingroup$ That's perfect!! That's the sort of simple solution I was hoping existed. If you write it as an answer I'll happily check it. If you or someone else wouldn't mind explaining, is there a reason to prefer either this solution or your Block solution? $\endgroup$ – Adam Jan 11 '14 at 2:14
  • $\begingroup$ Adam you should ping with a @ the user you talk to. I hadn't seen this last comment of yours. Both work in this case, but the Block solution is slightly more general, and is the general solution for what you explicitly asked for: "evaluate something for a particular choice of some symbol without it affecting the whole session" $\endgroup$ – Rojo May 30 '14 at 19:04
14
$\begingroup$

Using Block seems more appropriate

Block[{f}, f[x_]:=x^2;
expr]
$\endgroup$
6
$\begingroup$

Some different solutions to have this topic as a generic one:

expr = D[f[x y], x] + f[x, y]

expr /. f -> (#^2 &)
2 x + x^2

or more verbose:

expr /. f -> Function[x, x^2]
2 x + x^2

This functionality is also included in my dChange implementation from Analogue for Maple's dchange:

dChange[
   expr,
   f[x, y] == x^2
]
$\endgroup$
  • $\begingroup$ Thank you, this a nice solution! $\endgroup$ – Dr_Zaszuś Oct 17 '17 at 11:47

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.