# How to only print analytical solutions using DSolve

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],
Print[V[x]],
Print[DSolve[\!$$\*SubscriptBox[\(∂$$, $$x, x$$]$$ψ[ x]$$\) + (V[x] - ω^2) ψ[x] == 0, ψ[x], x]] //
FullSimplify},
{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.

• 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. Commented Nov 15, 2020 at 1:54

Clear["Global*"]

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

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


The results are stored in sol

?sol


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}]]


The results are still stored in the indexed variable sol

• 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. Commented Nov 15, 2020 at 12:41
• 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`. Commented Nov 15, 2020 at 16:35