Find a fraction's position in the Stern-Brocot tree The Stern-Brocot tree is a binary tree of fractions where each fraction is acquired by adding the numerators and denominators of the two fractions neighbouring it in the levels above.

It is generated by starting with 0/1 and 1/0 as "endpoint fractions", and from there, iterating by placing one fraction between each consecutive pair of fractions by adding the numerators and denominators of those fractions together, like so:

0.  0/1                                                             1/0
1.  0/1                             1/1                             1/0
2.  0/1             1/2             1/1             2/1             1/0
3.  0/1     1/3     1/2     2/3     1/1     3/2     2/1     3/1     1/0
4.  0/1 1/4 1/3 2/5 1/2 3/5 2/3 3/4 1/1 4/3 3/2 5/3 2/1 5/2 3/1 4/1 1/0


In each iteration of the Stern-Brocot tree (the nth iteration), there are 2^n + 1 elements in the sequence, to which we can ascribe a fraction from 0/2^n to 2^n/2^n. Each new iteration simply inserts one fraction "halfway" between each pair of consecutive fractions.

This makes the Stern-Brocot tree a one-to-one mapping between the positive rational numbers and the binary fractions between 0 and 1, thereby also serving as a proof that the two sets have the same cardinality.

Your task is to write a program or function that, given the numerator and denominator of a positive rational number in lowest terms, determines the binary fraction that corresponds to that fraction's position in the Stern-Brocot tree.

Examples of inputs and outputs are provided below:

2/3 -&gt; 3/8   (4th number in iteration 3)
4/7 -&gt; 9/32  (between 1/2 and 3/5 in the chart above)
1/1 -&gt; 1/2   (middle number in the first iteration)


Inputs you don't need to support, but are included for reference:

0/1 -&gt; 0/1   (0/1 is considered the left number)
1/0 -&gt; 1/1   (1/0 is considered the rightmost number)


The shortest program in any language to achieve this goal wins.
Ruby, 132 125

Rubied &amp; golfed the reference solution from @JoeZ.

def t(n,d)u=k=0;v,j,f,g,b=[1,]*5;c=2
while(z=(f*d).&lt;=&gt;(g*n))!=0;z&gt;0?(j,k=f,g):(u,v=f,g);b=b*2-z;f,g=u+j,v+k;c*=2;end
[b,c]end


Usage examples:

&gt;&gt; t(2,3)
=&gt; [3, 8]
&gt;&gt; t(4,7)
=&gt; [9, 32]
&gt;&gt; t(1,1)
=&gt; [1, 2]