
% Copyright (c) 1991-2002, The Numerical ALgorithms Group Ltd.
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
%     - Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%
%     - Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in
%       the documentation and/or other materials provided with the
%       distribution.
%
%     - Neither the name of The Numerical ALgorithms Group Ltd. nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
% IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
% TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
% PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
% OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
% EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
% PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES-- LOSS OF USE, DATA, OR
% PROFITS-- OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
% LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.



% Examples for ContinuedFraction
Continued fractions have been a fascinating and useful tool in mathematics
\index{fraction!continued}
for well over three hundred years.
\Language{} implements continued fractions for fractions of any Euclidean
\index{continued fraction}
domain.
In practice, this usually means rational numbers.
In this section we demonstrate some of the operations available for
manipulating both finite and infinite continued fractions.
It may be helpful if you review \xmpref{Stream} to remind yourself of some
of the operations with streams.

The \spadtype{ContinuedFraction} domain is a field and therefore you can
add, subtract, multiply and divide the fractions.
\xtc{
The \spadfunFrom{continuedFraction}{ContinuedFraction} operation
converts its fractional argument to a continued fraction.
}{
\spadcommand{c := continuedFraction(314159/100000) \bound{c}}
}
%
This display is a compact form of the bulkier
\begin{texonly}
\begin{displaymath}
3 + \cfrac{1}{
7 + \cfrac{1}{
15 + \cfrac{1}{
1 + \cfrac{1}{
25 + \cfrac{1}{
1 + \cfrac{1}{
7 + \cfrac{1}{4}}}}}}}
\end{displaymath}
\end{texonly}
\begin{htonly}
\begin{verbatim}
        3 +                 1
            -------------------------------
            7 +               1
                ---------------------------
                15 +            1
                     ----------------------
                     1 +          1
                         ------------------
                         25 +       1
                              -------------
                              1 +     1
                                  ---------
                                  7 +   1
                                      -----
                                        4
\end{verbatim}
\end{htonly}
You can write any rational number in a similar form.
The fraction will be finite and you can always take the ``numerators'' to
be \spad{1}.
That is, any rational number can be written as a simple, finite continued
fraction of the form
\begin{texonly}
\begin{displaymath}
a_1 + \cfrac{1}{
a_2 + \cfrac{1}{
a_3 + \cfrac{1}{\ddots
a_{n-1} + \cfrac{1}{a_n}}}}
\end{displaymath}
\end{texonly}
\begin{htonly}
\begin{verbatim}
        a(1) +           1
               -------------------------
               a(2) +          1
                      --------------------
                      a(3) +
                             .
                              .
                               .
                                     1
                               -------------
                               a(n-1) +  1
                                        ----
                                        a(n)
\end{verbatim}
\end{htonly}
\xtc{
The \texht{$a_i$}{\spad{a(i)}} are called partial quotients and the operation
\spadfunFrom{partialQuotients}{ContinuedFraction} creates a stream of them.
}{
\spadcommand{partialQuotients c \free{c}}
}
\xtc{
By considering more and more of the fraction, you get the
\spadfunFrom{convergents}{ContinuedFraction}.
For example, the first convergent is \texht{$a_1$}{\spad{a(1)}},
the second is
\texht{$a_1 + 1/a_2$}{\spad{a(1) + 1/a(2)}} and so on.
}{
\spadcommand{convergents c \free{c}}
}
%
\xtc{
Since this is a finite continued fraction, the last convergent is
the original rational number, in reduced form.
The result of \spadfunFrom{approximants}{ContinuedFraction}
is always an infinite stream, though it may just repeat the ``last''
value.
}{
\spadcommand{approximants c \free{c}}
}
\xtc{
Inverting \spad{c} only changes the partial quotients of its fraction
by inserting a \spad{0} at the beginning of the list.
}{
\spadcommand{pq := partialQuotients(1/c) \free{c}\bound{pq}}
}
\xtc{
Do this to recover the original continued fraction from this list of
partial quotients.
The three-argument form of the
\spadfunFrom{continuedFraction}{ContinuedFraction} operation takes an
element which is the whole part of the fraction, a stream of elements
which are the numerators of the fraction, and a stream of elements which
are the denominators of the fraction.
}{
\spadcommand{continuedFraction(first pq,repeating [1],rest pq) \free{pq}}
}
\xtc{
The streams need not be finite for
\spadfunFrom{continuedFraction}{ContinuedFraction}.
Can you guess which irrational number has the following continued
fraction?
See the end of this section for the answer.
}{
\spadcommand{z:=continuedFraction(3,repeating [1],repeating [3,6]) \bound{z}}
}
%

In 1737 Euler discovered the infinite continued fraction expansion
\begin{texonly}
\begin{displaymath}
\frac{e - 1}{2} =
\cfrac{1}{
1 + \cfrac{1}{
6 + \cfrac{1}{
10 + \cfrac{1}{
14 + \dotsb}}}}
\end{displaymath}
\end{texonly}
\begin{htonly}
\begin{verbatim}
        e - 1             1
        ----- = ---------------------
          2     1 +         1
                    -----------------
                    6 +       1
                        -------------
                        10 +    1
                             --------
                             14 + ...
\end{verbatim}
\end{htonly}
We use this expansion to compute rational and floating point
approximations of \spad{e}.\footnote{For this and other interesting
expansions, see C. D. Olds, {\it Continued Fractions,}
New Mathematical Library, (New York: Random House, 1963), pp.
134--139.}

\xtc{
By looking at the above expansion, we see that the whole part is \spad{0}
and the numerators are all equal to \spad{1}.
This constructs the stream of denominators.
}{
\spadcommand{dens : Stream Integer := cons(1, stream((x +-> x + 4), 6)) \bound{dens}}
}
\xtc{
Therefore this is the continued fraction expansion for
\texht{$(e - 1) / 2$}{\spad{(e-1)/2}}.
}{
\spadcommand{cf := continuedFraction(0,repeating [1],dens) \free{dens}\bound{cf}}
}
\xtc{
These are the rational number convergents.
}{
\spadcommand{ccf := convergents cf \free{cf}\bound{ccf}}
}
\xtc{
You can get rational convergents for \spad{e} by multiplying by \spad{2} and
adding \spad{1}.
}{
\spadcommand{eConvergents := [2*e + 1 for e in ccf] \bound{ec}\free{ccf}}
}
%
\xtc{
You can also compute the floating point approximations to these convergents.
}{
\spadcommand{eConvergents :: Stream Float \free{ec}}
}
\xtc{
Compare this to the value of \spad{e} computed by the
\spadfunFrom{exp}{Float} operation in \spadtype{Float}.
}{
\spadcommand{exp 1.0}
}

In about 1658, Lord Brouncker established the following expansion
for \texht{$4 / \pi$}{\spad{4/pi}}.
\begin{texonly}
\begin{displaymath}
1 + \cfrac{1}{
2 + \cfrac{9}{
2 + \cfrac{25}{
2 + \cfrac{49}{
2 + \cfrac{81}{
2 + \dotsb}}}}}
\end{displaymath}
\end{texonly}
\begin{htonly}
\begin{verbatim}
        1 +            1
            -----------------------
            2 +          9
                -------------------
                2 +        25
                    ---------------
                    2 +      49
                        -----------
                        2 +    81
                            -------
                            2 + ...
\end{verbatim}
\end{htonly}
\xtc{
Let's use this expansion to compute rational and floating point
approximations for \texht{$\pi$}{\spad{pi}}.
}{
\spadcommand{cf := continuedFraction(1,[(2*i+1)^2 for i in 0..],repeating [2])\bound{cf1}}
}
\xtc{
}{
\spadcommand{ccf := convergents cf \free{cf1}\bound{ccf1}}
}
\xtc{
}{
\spadcommand{piConvergents := [4/p for p in ccf] \bound{piConvergents}\free{ccf1}}
}
\xtc{
As you can see, the values are converging to
\texht{$\pi$}{\spad{pi}} = 3.14159265358979323846...,
but not very quickly.
}{
\spadcommand{piConvergents :: Stream Float \free{piConvergents}}
}

\xtc{
You need not restrict yourself to continued fractions of integers.
Here is an expansion for a quotient of Gaussian integers.
\index{Gaussian integer}
}{
\spadcommand{continuedFraction((- 122 + 597*\%i)/(4 - 4*\%i))}
}
\xtc{
This is an expansion for a quotient of polynomials in one variable
with rational number coefficients.
}{
\spadcommand{r : Fraction UnivariatePolynomial(x,Fraction Integer) \bound{rdec}}
}
\xtc{
}{
\spadcommand{r := ((x - 1) * (x - 2)) / ((x-3) * (x-4)) \free{rdec}\bound{r}}
}
\xtc{
}{
\spadcommand{continuedFraction r \free{r}}
}

\xtc{
To conclude this section, we give you evidence that
}{
\spadcommand{z \free{z}}
}
is the expansion of \texht{$\sqrt{11}$}{the square root of \spad{11}}.
%
\xtc{
}{
\spadcommand{[i*i for i in convergents(z) :: Stream Float] \free{z}}
}
\xtc{
}{
\spadcommand{continuedFraction sqrt 11.0}
}
