3
$\begingroup$

I'm having trouble making a function that uses the result of NDSolve:

c=1/4;
soln = NDSolve[{c^2*D[u[x, t], x, x] == D[u[x, t], t, t], 
         u[x, 0] == UnitTriangle[2*x - 1], 
         Derivative[0, 1][u][x, 0] == 0, u[0, t] == 0, 
         u[1, t] == 0}, u, {x, 0, 1}, {t, 0, 4/c}, 
     Method -> {"PDEDiscretization" -> {"MethodOfLines", 
             "SpatialDiscretization" -> "FiniteElement"}}]

energy[(t_)?NumericQ] := 
     (1/2)*NIntegrate[Evaluate[
           D[u[x, t]^2, t] + c^2*D[u[x, t]^2, x] /. 
               First[soln]], {x, 0, 1}, 
         MaxRecursion -> 10, Method -> "LocalAdaptive"]; 

Evaluating energy[0.5] gives the error: General::ivar: 0.5` is not a valid variable.

Inspecting the definition with ??energy shows Evaluate didn't work.

After changing the definition to:

expr = D[u[x, t]^2, t] + c^2*D[u[x, t]^2, x] /. First[soln];
energy[(t_)?NumericQ] := (1/2)*NIntegrate[Evaluate[expr], 
         {x, 0, 1}, MaxRecursion -> 10, 
         Method -> "LocalAdaptive"];

using energy[t] inside Table and Plot work, but energy[0.5] gives a NIntegrate::inumri error with NIntegrate left unevaluated and containing exactly what expr is.

$\endgroup$

1 Answer 1

5
$\begingroup$

You can't take derivative w.r.t. a number. You were passing t as number, then doing D[...,t]

Try the following. It is also easier to use NDSolveValue

ClearAll[u, x, t]
c = 1/4;
soln = NDSolveValue[{c^2*D[u[x, t], x, x] == D[u[x, t], t, t], 
    u[x, 0] == UnitTriangle[2*x - 1], Derivative[0, 1][u][x, 0] == 0, 
    u[0, t] == 0, u[1, t] == 0}, u, {x, 0, 1}, {t, 0, 4/c}, 
   Method -> {"PDEDiscretization" -> {"MethodOfLines", 
       "SpatialDiscretization" -> "FiniteElement"}}];
energy[t0_?NumericQ] := 
 Module[{t}, (1/2)*
   NIntegrate[
    D[soln[x, t]^2, t] + c^2*D[soln[x, t]^2, x] /. t -> t0, {x, 0, 1},
     MaxRecursion -> 10, Method -> "LocalAdaptive"]
  ]

And now

energy[0.5]

(*-0.093744*)
$\endgroup$
1
  • $\begingroup$ So what's going on with Evaluate? Isn't it supposed to evaluate an expression at the time of definition, regardless of the := ? And why does it work in Table and Plot? That's the behavior clearly given in the documentation on Evaluate under: "Force evaluation of the right-hand side of a delayed definition". $\endgroup$
    – user6552
    May 20 at 16:59

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.