How to substitute the result from FindRoot into another equation?

I have an equation $cos(k) = cos(q) + \frac{U_{0}}{q}sin(q),$ where the value of U runs from -2 to 2, and the value of k runs from $-\pi$ to $\pi.$ Now, I need to use the values of q to compute for $E = \frac{q^{2}}{2}.$ Lastly, I need to plot E vs. k. But I am having a problem in substituting the value of q into E. My code looks like this:

EmptyList = List[];
Do[Monitor[
roots =
FindRoot[
Cos[k] == Cos[q] + (1/q)*Sin[q], {q, \[Pi]}];
E[roots_] := roots^2/2;
AppendTo[EmptyList, {k, E}]
, {k, E}]
, {k, -\[Pi], \[Pi]}]
ListPlot[EmptyList]


EDITED1: I'll just $U_{0}=-1.$

EDITED2: My new code looks like this:

EmptyList = List[];
Do[Monitor[
var = FindRoot[Cos[k] == Cos[q] + (1/q)*Sin[q], {q, \[Pi]}];
energy = var^2/2;
AppendTo[EmptyList, {k, energy}];
, {k, energy}]
, {k, -\[Pi], \[Pi]}]


EmptyList has this value:

{{-\[Pi], {1/2 (q -> 3.14159)^2}}, {1 - \[Pi], {1/
2 (q -> 2.47905)^2}}, {2 - \[Pi], {1/
2 (q -> -1.72719)^2}}, {3 - \[Pi], {1/
2 (q -> 1.31405)^2}}, {4 - \[Pi], {1/
2 (q -> -1.55868)^2}}, {5 - \[Pi], {1/
2 (q -> 2.25107)^2}}, {6 - \[Pi], {1/2 (q -> 3.03703)^2}}}

• You can start by not using E as function name, since E is special function in Mathematica. Why not run each line of code on its own first and see what it does? Even your FindRoot gives error. Feb 28 '18 at 6:37
• Okay, I'll try it. Thanks. Feb 28 '18 at 6:42

2 Answers

I would propose you to use Table instead of Do. This way, for example:

lst1 = Table[{k, FindRoot[Cos[k] == Cos[q] + (1/q)*Sin[q], {q, \[Pi]}][[1,2]]}, {k, -\[Pi], \[Pi], 0.1}];


This yields a rather strange result q=q(k) with discontinuities:

ListPlot[lst1, AxesLabel -> {Style["k", 16, Italic], Style["q", 16, Italic]}]


Be aware of the fact that if you take a different initial guess for the FindRoot, say, k, then the result will be quite different.

lst2 = Table[{k, FindRoot[Cos[k] == Cos[q] + (1/q)*Sin[q], {q, k}][[1,
2]]}, {k, -\[Pi], \[Pi], 0.1}];

ListPlot[lst2, AxesLabel -> {Style["k", 16, Italic], Style["q", 16, Italic]}]


Which one of these two (and probably some others) is right is up to you.

Have fun!

• Alexei Boulbitch, thanks a lot! Mar 1 '18 at 8:52

I have already solved it. I just added q /. in var (line3):

EmptyList = List[];
Do[Monitor[
var = q /. FindRoot[Cos[k] == Cos[q] + (1/q)*Sin[q], {q, \[Pi]}];
energy = var^2/2;
AppendTo[EmptyList, {k, energy}];
, {k, energy}]
, {k, -\[Pi], \[Pi], 0.01}]