5
$\begingroup$

I'm having problems working with the output from DSolve whilst in a module. To handle the result outside a module typically I would do something like

 f[t] = y[t] /. solution

But inside a module my t is now t$ followed by some numbers. How can I create and return a function from the output of DSolve inside a module?


Here is my code:

Module[{equations,solution,h,t},
  m=1;
  g=9.8;
  equations = {y''[t]== -m g,y'[0]==100,y[0]==0};
  solution = Flatten@ DSolve[equations,y,t];
  h[t] = y[t] /. solution;
  h[1]]

I get h = 100. t$16608-4.9 t$16608^2, but h[1] = h$16909[1).

$\endgroup$
3
  • 1
    $\begingroup$ OK, it is not clear what you try to achieve. There is an architectural error if you try to return an lokal variable like h. Furthermore, (in your additional post) you don't return a function! You return only an expression. Can you please clear up what exactly you try and how you want to use it? Btw, you can edit your question and improve it. Don't write an additional post. $\endgroup$
    – halirutan
    Commented Feb 27, 2013 at 10:05
  • $\begingroup$ I think the most straightforward answer is just "use Block rather than Module in this case", so I voted to close this as a duplicate of a question the explains the distinctions rather well. $\endgroup$ Commented Mar 28, 2013 at 23:08
  • 1
    $\begingroup$ See reference.wolfram.com/mathematica/tutorial/… You're using Set (=) instead of SetDelayed (:=); and you should use a pattern h[t_]. You could also simply skip h and return y[1] /. solution. $\endgroup$
    – Michael E2
    Commented Mar 29, 2013 at 11:42

2 Answers 2

2
$\begingroup$

If I understand you correctly, you can use DSolve[eqs, y, t] instead of DSolve[eqs, y[t], t] to get a rule like y -> Function[ arg, ... ], so the t, whether it's local or not, will not make difference.

Module[{t}, DSolve[y'[t] == t, y, t] ]
{{y -> Function[{t$31879}, t$31879^2/2 + C[1]]}}
y[t] /. %
{t^2/2 + C[1]}
$\endgroup$
2
$\begingroup$

You could return a pure function. Like this

m = 1;
g = 9.8;

h = Module[{equations, solution, t},
      equations = {y''[t] == -m g, y'[0] == 100, y[0] == 0};
      solution = First@Flatten@DSolve[equations, y[t], t];
      With[{x = Last @solution /. t -> #1}, x &]]
100. #1 - 4.9 #1^2 &
 h[1]

95.1

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.