0
$\begingroup$

The following is a really simplified version of what I'm trying to do. I have a variable fn defined in terms some other variable x. I then want to define a function of x through the variable fn.

fn = x^2;
f[x_] := fn
f[2]

However, Mathematica doesn't like it. For f[2] it just spits out $x^2$. How can I make this work? (In my complicated case I really don't want to define a function fn[x_]:=x^2 and then define f[x_]:=fn[x_])

Edit: It has been suggested to use Evaluate@fn. Which indeed works. However, let me propose a different example that doesn't work:

fn = x^2 a^2;
f[x_] := NIntegrate[Evaluate@fn, {a, -1, 1}]
f[2]

(and similarly if I put Evaluate@NIntegrate instead)

$\endgroup$
3
  • $\begingroup$ try f[x_] := Evaluate@fn it is because you used delayed assignment. If you used f[x_] = fn then it would have worked. But delayed is better in general. You just need to know the difference between = and := in Mathematica. These have different semantics. ps. this type of question has been asked before few times,. I am sure it is somewhere in what-are-the-most-common-pitfalls-awaiting-new-users/ $\endgroup$
    – Nasser
    Commented Dec 23, 2023 at 22:03
  • $\begingroup$ Thank you @Nasser, see my edit in the question above. $\endgroup$
    – Rudyard
    Commented Dec 23, 2023 at 22:19
  • $\begingroup$ The only real answer is: you shouldn't be doing this in the first place. Mathematica doesn't like it for a reason. In any case you may want to look into Block. $\endgroup$ Commented Dec 23, 2023 at 22:48

1 Answer 1

2
$\begingroup$

It would be better if we know why you had things set up this way, because it looks like your fighting against the evaluation engine here, but as a workaround, you could do something like this:

(* make a legit function *)
f = Function[x, Evaluate[fn]]

(* use it in your integration function *)
fInt[x_] := NIntegrate[f[x], {a, -1, 1}]

This forces the x to get replaced first when you call fInt.

$\endgroup$

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.