3.2. Continued fraction expansion

For the classical number theoretic part of Shor’s algorithm we’ll need to know how to do a continued fraction expansion. This allows us to write a real number in terms of integers as a type of fraction. For rational numbers this fraction will terminate, but it generally won’t terminate for non-rationals. We will only encounter rational numbers in our discussion. We illustrate with an example:

  1. We want to write 31/14 as a continued fraction, so we first break it into its integer and fraction parts, and then invert the fractional part:$$\frac{31}{14}=2+\frac{3}{14}=2+\frac{1}{\frac{14}{3}}.$$
  2. Repeat the integer-fraction split and inversion steps until the final numerator is unity:$$\frac{31}{14}=2+\frac{1}{4+\frac{1}{1+\frac{1}{2}}}.$$You will know that the continued fraction has terminated because an inversion step here would not achieve anything.

In general we continue until either the fraction terminates or, for non-rational numbers, until we have reached an acceptable level of precision. You may see the notation \([a_0; a_1, a_2, \dots]\) to represent fractions of this type, equivalent to$$a_0+\frac{1}{a_1+\frac{1}{a_2+\dots}}$$so our example of 31/14 becomes \([2; 4, 1, 2]\). The integer part comes before the semi-colon.

We’ll also want to know how to calculate what are called the convergents of a continued fraction. These are increasingly accurate rational approximations to a continued fraction, and are given iteratively by the formula$$C_i=\frac{p_i}{q_i}=\frac{a_ip_{i-1}+p_{i-2}}{a_iq_{i-1}+q_{i-2}}$$where \(p_0=a_0,p_{-1}=1,q_0=1,q_{-1}=0\). In general, for a continued fraction expansion with \(n\) elements, the \(n\)th element will be exact. Using this formula, you should be able to form the following convergents of \(31/14 = [2;4,1,2]\):$$
C_0 = 2,\quad C_1=2.25,\quad C_2=2.2,\quad C_3=31/14.$$We clearly see the sequence converging on the true value, with the fourth iteration being exact for a four-element continued fraction. The convergent with denominator \(q\) is provably the best approximation possible with a denominator less than or equal to \(q\).