I would like to create a code that keep on trying to solve a differential equation for different values of a parameter, in this case $ a $. But it must print only when it has an analytical solution.

A simple example follows:

V[x_] := Sin[x]^a;
Do[{Print["a = ", a],
\*SubscriptBox[\(∂\), \(x, x\)]\(ψ[
         x]\)\) + (V[x] - ω^2) ψ[x] == 0, ψ[x], x]] //
 {a, 0, 2}

It is obvious that this has an analytical solution for $ a = 0 $, but it will still print something for the other values. How do I get an If condition that tells Mathematica to not print if an analytical solution was not found?

And any other suggestion on how to make this more efficient is welcome, since my problem is far more complicated than this.

  • 1
    $\begingroup$ Replace Print[DSolve[...]] with FullSimplify[ DSolve[\[Psi]''[x] + (V[x] - \[Omega]^2) \[Psi][x] == 0, \[Psi][x], x]] /. res_?ListQ :> Print[res]? Note your original FullSimplify was outside Print and had no effect. $\endgroup$
    – Michael E2
    Commented Nov 15, 2020 at 1:54

1 Answer 1


V[x_] := Sin[x]^a;

 Table[temp = DSolveValue[
      ψ''[x] + (V[x] - ω^2) ψ[x] == 0, ψ[x], x];
    If[FreeQ[temp, _DSolveValue], {a, (sol[a] = temp // FullSimplify) // 
       TraditionalForm}, Nothing],
    {a, -4, 4}] //
   Prepend[#, (Style[#, 12, Bold] & /@ {"a", "ψ(x)"})] & //
  Grid[#, Frame -> All] &]

enter image description here

The results are stored in sol


enter image description here

EDIT: For an incremental output

Module[{temp}, Table[temp = DSolveValue[
    ψ''[x] + (V[x] - ω^2) ψ[x] == 0, ψ[x], x];
  If[FreeQ[temp, _DSolveValue], Print[StringForm[
     "With a=``, ψ(x)=``;", 
     a, (sol[a] = temp // FullSimplify) // TraditionalForm]]; Nothing, 
   Nothing], {a, -4, 4}]]

enter image description here

The results are still stored in the indexed variable sol

  • $\begingroup$ It works, but I have no idea why. Could you briefly explain me, please? It it possible to change it to print a found solution whenever it is found, since my problem is going to take much longer to run, and I would like to check if it found something on the go. $\endgroup$ Commented Nov 15, 2020 at 12:41
  • $\begingroup$ In the Table, (1) a is given its value, (2) DSolveValue attempts to find \[Psi][x] and temp is temporarily Set to either \[Psi][x] or the unevaluated DSolveValue, (3) If temp does not contain an expression with Head of DSolveValue, the indexed variable sol is Set to temp (i.e., \[Psi][x]), (4) the If evaluates to either {a, \[Psi][x]} or Nothing; the rest is formatting of the Grid. $\endgroup$
    – Bob Hanlon
    Commented Nov 15, 2020 at 16:35

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.