# How to plot a graph for the solution to a differential equation

I am very new to Mathematica and am struggling to get a plot for a differential equation I need solving. I am doing a simplified version of the lane-emden equation for n=1 so have the follwoing equation to be solved $$\frac{1}{x^2}\frac{d}{dx}\left(x^2\frac{df(x)}{dx}\right)+f(x)=f''(x)+2\frac{f'(x)}{x}+f(x)$$ Since it has a singularity at zero, I have using the following approximation for near the origin:

series[x_] := 1 + x^2(-1/6) +x^4(1/120)


So my equation I want to be able to plot is the following:

sol = f[x] /. NDSolve[{f[x] + 2f'[x]/x +f''[x] == 0, f[0.1] == series[0.1], f'[0.1] == series[0.1]}, f, {x, 0.1, 4}]


When I do:

Plot[sol, {x, 0.1, 4}]


I just get an empty axis and no graph so I really don't know why it won't work or how to fix it. Any ideas?

• 1) Use := to define functions like series rather than =. 2) Your boundary conditions need to be expressed as equations, using == (Equal) and not = (Set). Make sure to run ClearAll[f] before your fixed code. 3) You can't have a non-numerical symbolic value like x0 when you seek a numerical solution to your equation. If the solution is parametric, then use ParametricNDSolve; if x0 has a value, then please include it in your definitions. Commented Apr 20, 2022 at 15:37

Your simplified equation can be solved analytically:

sol =
DSolve[
{f''[x] + 2 f'[x]/x + f[x] == 0,
f[1/10] == series[1/10],
f'[1/10] == series[1/10]
},
f, x
]


The use of your series expansion introduces the parameter x0. Since you don't provide values for it, I've chosen to show the results for $$x_0=1,2,3$$ below. Note also that the numerical values contain small imaginary components that are due to numerical inaccuracies; you can get rid of those with Chop.

Plot[
Evaluate@Chop[f[x] /. sol /. x0 -> {1, 2, 3}],
{x, 0.1, 4}
]


• Using that DSolve function that you have, I am getting the error that 0 is not a valid variable? Commented Apr 20, 2022 at 15:54
• You seem to be getting it but when I try and replicate it, it just isn't working for me? Commented Apr 20, 2022 at 15:55
• @JordynTaylor The code shown to you works without any issues for me; V13.0.0. I had to grab the first definition of series[x] that contained a free parameter. Try to Quit[] or ClearAll["Global*"]` and the solution should be working fine!
– bmf
Commented Apr 20, 2022 at 17:21