2

I am sure this has been asked before, but I can't seem to find the right solution.

I want a function to be the solution to a differential equation

refun[u_, rem_, reengy_] = 
 DSolveValue[{D[D[fun[u], u], u] + (-rem^2 + 1/4)/u^2*fun[u] - 
       u^2*fun[u] + reengy*fun[u] == 0}, fun[u], u] /. C[1] -> 0 /. 
  C[2] -> 1

which works out perfectly. But if I accidentally write

rem=1
refun[u_, rem_, reengy_] = 
 DSolveValue[{D[D[fun[u], u], u] + (-rem^2 + 1/4)/u^2*fun[u] - 
       u^2*fun[u] + reengy*fun[u] == 0}, fun[u], u] /. C[1] -> 0 /. 
  C[2] -> 1

the value of rem is fixed to 1 no matter what I specify as a function argument. If I were to use := to define the function I would not have this problem, but then the differential equation would be solved each time I call the function.

This seems to be a scoping issue and I tried to play around with Module and Block but couldn't get it to work. How can I protect my function from it's variables being altered by accident? Any suggestion is highly appreciated.

Kuba
  • 136,707
  • 13
  • 279
  • 740
ftiaronsem
  • 665
  • 4
  • 13

1 Answers1

5

You should use Block to keep external definition from being substituted while the RHS of the definition is being evaluated.

rem = 1;
Block[{u, rem, reengy, fun}, 
  refun[u_, rem_, reengy_] = 
   DSolveValue[{D[D[fun[u], u], u] + (-rem^2 + 1/4)/u^2*fun[u] - 
         u^2*fun[u] + reengy*fun[u] == 0}, fun[u], u] /. C[1] -> 0 /. C[2] -> 1];

Definition[refun]
(*
  refun[u_, rem_, reengy_] = (2^((1 + rem)/2) E^(u^2/2) (u^2)^((1 + rem)/2)
     LaguerreL[1/4 (-2 - reengy - 2 rem), rem, -u^2])/Sqrt[u]
*)
Michael E2
  • 235,386
  • 17
  • 334
  • 747