0
$\begingroup$

The following is the code for Kronig-Penney model from the book A Physicist's Guide to Mathematica by Patrick T. Tam. I would be grateful if someone could explain the code to me, especially line with FindRoot. What is the role of [[1, 2]] there?

kmPlot[l_?Positive, nb_Integer?Positive, mp_Integer /; mp > 10] :=
  Module[{K, Q, d, r},
   K[n_, 1] := n*Pi;
   Q[n_, m_] := n*Pi - (m - 1)*Pi/(mp - 1);
   K[n_, m_] :=  
     K[n, m] = 
       FindRoot[Cos[Q[n, m]] == Cos[x] + (l/2)*(Sin[x]/x), {x,K[n, m - 1]}][[1, 2]];
   d[n_, m_] := K[n, m]^2;
   r[n_] := r[n] = Table[{Q[n, m], d[n, m]}, {m, 1, mp}];
   Graphics[
     Flatten[Table[{Line[r[n]], Line[{-#[[1]], #[[2]]} & /@ r[n]]}, {n,1, nb}]], 
     Ticks ->  {Table[{I*Pi, I "p"}, {I, -nb, nb}], Automatic}, 
     Axes -> True, AxesLabel -> {"q(1/a)", "E"}, 
     AspectRatio -> 1/GoldenRatio]];
$\endgroup$
1
  • 3
    $\begingroup$ Common pitfalls / What the @#%^&*?! do all those funny signs mean? / Other $\endgroup$
    – Kuba
    Mar 3, 2017 at 9:21

1 Answer 1

2
$\begingroup$

It is easy, given Mathematica's highly interactive nature, to answer questions like this yourself by making some simple experiments.

First it is alway good to look at strange notation with FullForm, which will shows you the internal form. Hold is used here to suppress evaluation of the form. This tells you that you should consult Part in the documentation.

 Hold[x[[1, 2]]] // FullForm

Hold[Part[x, 1, 2]]

Next compare what FindRoot produces with and without [[1, 2]].

 FindRoot[Sin[x] == x/2, {x, 2}]

{x -> 1.89549}

 FindRoot[Sin[x] == x/2, {x, 2}][[1, 2]]

1.89549

So you see that [[1, 2]] is used to extract the value of the root from the expression returned by FindRoot.

$\endgroup$
2
  • 1
    $\begingroup$ Just to note, x /. FindRoot[Sin[x] == x/2, {x, 2}] would be a more transparent way to achieve the same goal. $\endgroup$
    – Chris K
    Mar 3, 2017 at 12:21
  • $\begingroup$ Thanks a lot m_goldberg. I did not know about Hold.Thanks a lot. $\endgroup$ Mar 3, 2017 at 12:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.