TITLE: Computing Ancestors of # for Stern-Brocot Tree
QUESTION [6 upvotes]: Reading about the Stern-Brocot tree, the article gives this example:

using 7/5 as an example, its closest smaller ancestor is 4/3, so its left child is (4 + 7)/(3 + 5) = 11/8, and its closest larger ancestor is 3/2, so its right child is (7 + 3)/(5 + 2) = 10/7.

Getting the left and right children seem clear to me:

left - mediant of # (7/5) and closest smaller ancestor (4/3)
right- mediant of # (7/5) and closest larger  ancestor (3/2)

But, how can I figure out the closest smaller and larger ancestors of 7/5?

REPLY [2 votes]: A well known property of the Stern-Brocot tree is that there exists a one to one correspondence
between the fractions in the interval $[0,1]$ and the fractions in the interval
$[1,\infty]$. But it's much simpler to initialize the tree with the interval $[0,1]$.
Doing so we get the (Pascal) algorithm below for travelling two paths in
the Stern-Brocot tree that lead us to the fraction $5/7$ by enclosing it between
a lower bound $m1/n1$ and an upper bound $m2/n2$ with each step. The algorithm
halts because it is known that any rational number is in the tree.

program Kevin;
procedure Stern_Brocot(teller,noemer : integer);
{
  Walk through Stern-Brocot tree
  until fraction = teller/noemer
 (English: numerator/denominator)
}
var
  m1,m2,n1,n2 : integer;
begin
{ Initialize tree }
  m1 := 0; n1 := 1;
  m2 := 1; n2 := 0;
  while true do
  begin
  { if teller/noemer < (m1+m2)/(n1+n2) then }
    if (n1+n2)*teller < (m1+m2)*noemer then
  { Tightening }
    begin
    { Upper Bound }
      m2 := m1+m2;
      n2 := n1+n2;
    end else begin
    { Lower Bound }
      m1 := m1+m2;
      n1 := n1+n2;
    end;
    Writeln(m1,'/',n1,' < ',teller,'/',noemer,' < ',m2,'/',n2);
    if (teller/noemer = m1/n1)
    or (teller/noemer = m2/n2) then Break;
  end;
end;
begin
  Stern_Brocot(5,7);
end.

Output:

0/1 < 5/7 < 1/1
1/2 < 5/7 < 1/1
2/3 < 5/7 < 1/1
2/3 < 5/7 < 3/4
5/7 < 5/7 < 3/4

From this output we derive the required sequence by hand (oh well, the whole
thing could have been done by hand in this simple case, but it's useful to have
such a computer program for e.g. approximating irrational numbers).

1/1 < 7/5 < 1/0
1/1 < 7/5 < 2/1
1/1 < 7/5 < 3/2
4/3 < 7/5 < 3/2
4/3 < 7/5 < 7/5

Note that the closest smaller and larger ancestors are in the tree just before the algorithm halts.
EDIT. My favorite reference is this:

Stern-Brocot Tree

More impressive examples are obtained by calculating for
irrational numbers, such as $1/\sqrt{2}$:

if (n1+n2)*(n1+n2) < (m1+m2)*(m1+m2)*2 then

Giving, after e.g. 45 iterations:
$$
\frac{318281039}{225058681} < \sqrt{2} < \frac{768398401}{543339720}
$$