
          E02 -- Curve and Surface Fitting              Introduction -- E02
                                    Chapter E02
                             Curve and Surface Fitting

          Contents of this Introduction:

          1.     Scope of the Chapter

          2.     Background to the Problems

          2.1.   Preliminary Considerations

          2.1.1. Fitting criteria: norms

          2.1.2. Weighting of data points

          2.2.   Curve Fitting

          2.2.1. Representation of polynomials

          2.2.2. Representation of cubic splines

          2.3.   Surface Fitting

          2.3.1. Bicubic splines: definition and representation

          2.4.   General Linear and Nonlinear Fitting Functions

          2.5.   Constrained Problems

          2.6.   References

          3.     Recommendations on Choice and Use of Routines

          3.1.   General

          3.1.1. Data considerations

          3.1.2. Transformation of variables

          3.2.   Polynomial Curves

          3.2.1. Least-squares polynomials: arbitrary data points

          3.2.2. Least-squares polynomials: selected data points

          3.3.   Cubic Spline Curves

          3.3.1. Least-squares cubic splines

          3.3.2. Automatic fitting with cubic splines

          3.4.   Spline Surfaces

          3.4.1. Least-squares bicubic splines

          3.4.2. Automatic fitting with bicubic splines

          3.5.   General Linear and Nonlinear Fitting Functions

          3.5.1. General linear functions

          3.5.2. Nonlinear functions

          3.6.   Constraints

          3.7.   Evaluation, Differentiation and Integration

          3.8.   Index



          1. Scope of the Chapter

          The main aim of this chapter is to assist the user in finding a
          function which approximates a set of data points. Typically the
          data contain random errors, as of experimental measurement, which
          need to be smoothed out. To seek an approximation to the data, it
          is first necessary to specify for the approximating function a
          mathematical form (a polynomial, for example) which contains a
          number of unspecified coefficients: the appropriate fitting
          routine then derives for the coefficients the values which
          provide the best fit of that particular form. The chapter deals
          mainly with curve and surface fitting (i.e., fitting with
          functions of one and of two variables) when a polynomial or a
          cubic spline is used as the fitting function, since these cover
          the most common needs. However, fitting with other functions
          and/or more variables can be undertaken by means of general
          linear or nonlinear routines (some of which are contained in
          other chapters) depending on whether the coefficients in the
          function occur linearly or nonlinearly. Cases where a graph
          rather than a set of data points is given can be treated simply
          by first reading a suitable set of points from the graph.

          The chapter also contains routines for evaluating,
          differentiating and integrating polynomial and spline curves and
          surfaces, once the numerical values of their coefficients have
          been determined.

          2. Background to the Problems

          2.1. Preliminary Considerations

          In the curve-fitting problems considered in this chapter, we have
          a dependent variable y and an independent variable x, and we are
          given a set of data points (x ,y ), for r=1,2,...,m. The
                                       r  r
          preliminary matters to be considered in this section will, for
          simplicity, be discussed in this context of curve-fitting
          problems. In fact, however, these considerations apply equally
          well to surface and higher-dimensional problems. Indeed, the
          discussion presented carries over essentially as it stands if,
          for these cases, we interpret x as a vector of several
          independent variables and correspondingly each x  as a vector
                                                          r
          containing the rth data value of each independent variable.

          We wish, then, to approximate the set of data points as closely
          as possible with a specified function, f(x) say, which is as
          smooth as possible -- f(x) may, for example, be a polynomial. The
          requirements of smoothness and closeness conflict, however, and a
          balance has to be struck between them. Most often, the smoothness
          requirement is met simply by limiting the number of coefficients
          allowed in the fitting function -- for example, by restricting
          the degree in the case of a polynomial. Given a particular number
          of coefficients in the function in question, the fitting routines
          of this chapter determine the values of the coefficients such
          that the 'distance' of the function from the data points is as
          small as possible. The necessary balance is struck by the user
          comparing a selection of such fits having different numbers of
          coefficients. If the number of coefficients is too low, the
          approximation to the data will be poor. If the number is too
          high, the fit will be too close to the data, essentially
          following the random errors and tending to have unwanted
          fluctuations between the data points. Between these extremes,
          there is often a group of fits all similarly close to the data
          points and then, particularly when least-squares polynomials are
          used, the choice is clear: it is the fit from this group having
          the smallest number of coefficients.

          The above process can be seen as the user minimizing the
          smoothness measure (i.e., the number of coefficients) subject to
          the distance from the data points being acceptably small. Some of
          the routines, however, do this task themselves. They use a
          different measure of smoothness (in each case one that is
          continuous) and minimize it subject to the distance being less
          than a threshold specified by the user. This is a much more
          automatic process, requiring only some experimentation with the
          threshold.

          2.1.1.  Fitting criteria: norms

          A measure of the above 'distance' between the set of data points
          and the function f(x) is needed. The distance from a single data
          point (x ,y ) to the function can simply be taken as
                  r  r

                              (epsilon) =y -f(x ),                      (1)
                                       r  r    r

          and is called the residual of the point. (With this definition,
          the residual is regarded as a function of the coefficients
          contained in f(x); however, the term is also used to mean the
          particular value of (epsilon)  which corresponds to the fitted
                                       r
          values of the coefficients.) However, we need a measure of
          distance for the set of data points as a whole. Three different
          measures are used in the different routines (which measure to
          select, according to circumstances, is discussed later in this
          sub-section). With (epsilon)  defined in (1), these measures, or
                                      r
          norms, are

                                m
                                --
                                >  |(epsilon) |,                        (2)
                                --           r
                                r=1

                                 

                                / m
                               /  --          2
                              /   >  (epsilon) ,  and                   (3)
                             /    --          r
                           \/     r=1

                               max |(epsilon) |,                        (4)
                                  r          r

          respectively the l  norm, the l  norm and the l      norm.
                            1            2               infty

          Minimization of one or other of these norms usually provides the
          fitting criterion, the minimization being carried out with
          respect to the coefficients in the mathematical form used for
          f(x): with respect to the b  for example if the mathematical form
                                     i
          is the power series in (8) below. The fit which results from
          minimizing (2) is known as the l  fit, or the fit in the l  norm:
                                          1                         1
          that which results from minimizing (3) is the l  fit, the well-
                                                         2
          known least-squares fit (minimizing (3) is equivalent to
          minimizing the square of (3), i.e., the sum of squares of
          residuals, and it is the latter which is used in practice), and
          that from minimizing (4) is the l     , or minimax, fit.
                                           infty

          Strictly speaking, implicit in the use of the above norms are the
          statistical assumptions that the random errors in the y  are
                                                                 r
          independent of one another and that any errors in the x  are
                                                                 r
          negligible by comparison. From this point of view, the use of the
          l  norm is appropriate when the random errors in the y  have a
           2                                                    r
          normal distribution, and the l      norm is appropriate when they
                                        infty
          have a rectangular distribution, as when fitting a table of
          values rounded to a fixed number of decimal places. The l  norm
                                                                   1
          is appropriate when the error distribution has its frequency
          function proportional to the negative exponential of the modulus
          of the normalised error -- not a common situation.

          However, the user is often indifferent to these statistical
          considerations, and simply seeks a fit which he can assess by
          inspection, perhaps visually from a graph of the results. In this
          event, the l  norm is particularly appropriate when the data are
                      1
          thought to contain some 'wild' points (since fitting in this norm
          tends to be unaffected by the presence of a small number of such
          points), though of course in simple situations the user may
          prefer to identify and reject these points. The l      norm
                                                           infty
          should be used only when the maximum residual is of particular
          concern, as may be the case for example when the data values have
          been obtained by accurate computation, as of a mathematical
          function. Generally, however, a routine based on least-squares
          should be preferred, as being computationally faster and usually
          providing more information on which to assess the results. In
          many problems the three fits will not differ significantly for
          practical purposes.

          Some of the routines based on the l  norm do not minimize the
                                             2
          norm itself but instead minimize some (intuitively acceptable)
          measure of smoothness subject to the norm being less than a user-
          specified threshold. These routines fit with cubic or bicubic
          splines (see (10) and (14) below) and the smoothing measures
          relate to the size of the discontinuities in their third
          derivatives. A much more automatic fitting procedure follows from
          this approach.

          2.1.2.  Weighting of data points

          The use of the above norms also assumes that the data values y
                                                                        r
          are of equal (absolute) accuracy. Some of the routines enable an
          allowance to be made to take account of differing accuracies. The
          allowance takes the form of 'weights' applied to the y-values so
          that those values known to be more accurate have a greater
          influence on the fit than others. These weights, to be supplied
          by the user, should be calculated from estimates of the absolute
          accuracies of the y-values, these estimates being expressed as
          standard deviations, probable errors or some other measure which
          has the same dimensions as y. Specifically, for each y  the
                                                                r
          corresponding weight w  should be inversely proportional to the
                                r
          accuracy estimate of y . For example, if the percentage accuracy
                                r
          is the same for all y , then the absolute accuracy of y  is
                               r                                 r
          proportional to y  (assuming y  to be positive, as it usually is
                           r            r
          in such cases) and so w =K/y , for r=1,2,...,m, for an arbitrary
                                 r    r
          positive constant K. (This definition of weight is stressed
          because often weight is defined as the square of that used here.)
          The norms (2), (3) and (4) above are then replaced respectively
          by

                               m
                               --
                               >  |w (epsilon) |,                       (5)
                               --   r         r
                               r=1

                                

                               / m
                              /  --  2         2
                             /   >  w (epsilon) ,  and                  (6)
                            /    --  r         r
                          \/     r=1

                              max |w (epsilon) |.                       (7)
                                 r  r         r

          Again it is the square of (6) which is used in practice rather
          than (6) itself.

          2.2. Curve Fitting

          When, as is commonly the case, the mathematical form of the
          fitting function is immaterial to the problem, polynomials and
          cubic splines are to be preferred because their simplicity and
          ease of handling confer substantial benefits. The cubic spline is
          the more versatile of the two. It consists of a number of cubic
          polynomial segments joined end to end with continuity in first
          and second derivatives at the joins. The third derivative at the
          joins is in general discontinuous. The x-values of the joins are
          called knots, or, more precisely, interior knots. Their number
          determines the number of coefficients in the spline, just as the
          degree determines the number of coefficients in a polynomial.

          2.2.1.  Representation of polynomials

          Rather than using the power-series form

                                           2        k
                           f(x)==b +b x+b x +...+b x                    (8)
                                  0  1   2        k

          to represent a polynomial, the routines in this chapter use the
          Chebyshev series form

                         1
                  f(x)== -a T (x)+a T (x)+a T (x)+...+a T (x),          (9)
                         2 0 0     1 1     2 2         k k

          where T (x) is the Chebyshev polynomial of the first kind of
                 i
          degree i (see Cox and Hayes [1], page 9), and where the range of
          x has been normalised to run from -1 to +1. The use of either
          form leads theoretically to the same fitted polynomial, but in
          practice results may differ substantially because of the effects
          of rounding error. The Chebyshev form is to be preferred, since
          it leads to much better accuracy in general, both in the
          computation of the coefficients and in the subsequent evaluation
          of the fitted polynomial at specified points. This form also has
          other advantages: for example, since the later terms in (9)
          generally decrease much more rapidly from left to right than do
          those in (8), the situation is more often encountered where the
          last terms are negligible and it is obvious that the degree of
          the polynomial can be reduced (note that on the interval -1<=x<=1
          for all i, T (x) attains the value unity but never exceeds it, so
                      i
          that the coefficient a  gives directly the maximum value of the
                                i
          term containing it).

          2.2.2.  Representation of cubic splines

          A cubic spline is represented in the form

                      f(x)==c N (x)+c N (x)+...+c N (x),               (10)
                             1 1     2 2         p p

          where N (x), for i=1,2,...,p, is a normalised cubic B-spline (see
                 i
          Hayes [2]). This form, also, has advantages of computational
          speed and accuracy over alternative representations.

          2.3. Surface Fitting

          There are now two independent variables, and we shall denote
          these by x and y. The dependent variable, which was denoted by y
          in the curve-fitting case, will now be denoted by f. (This is a
          rather different notation from that indicated for the general-
          dimensional problem in the first paragraph of Section 2.1 , but
          it has some advantages in presentation.)

          Again, in the absence of contrary indications in the particular
          application being considered, polynomials and splines are the
          approximating functions most commonly used. Only splines are used
          by the surface-fitting routines in this chapter.

          2.3.1.  Bicubic splines: definition and representation

          The bicubic spline is defined over a rectangle R in the (x,y)
          plane, the sides of R being parallel to the x- and y-axes. R is
          divided into rectangular panels, again by lines parallel to the
          axes. Over each panel the bicubic spline is a bicubic polynomial,
          that is it takes the form

                                3   3
                                --  --     i j
                                >   >  a  x y .                        (13)
                                --  --  ij
                                i=0 j=0

          Each of these polynomials joins the polynomials in adjacent
          panels with continuity up to the second derivative. The constant
          x-values of the dividing lines parallel to the y-axis form the
          set of interior knots for the variable x, corresponding precisely
          to the set of interior knots of a cubic spline. Similarly, the
          constant y-values of dividing lines parallel to the x-axis form
          the set of interior knots for the variable y. Instead of
          representing the bicubic spline in terms of the above set of
          bicubic polynomials, however, it is represented, for the sake of
          computational speed and accuracy, in the form

                                 p   q
                                 --  --
                         f(x,y)= >   >  c  M (x)N (y),                 (14)
                                 --  --  ij i    j
                                 i=1 j=1

          where M (x), for i=1,2,...,p, and N (y), for j=1,2,...,q, are
                 i                           j
          normalised B-splines (see Hayes and Halliday [4] for further
          details of bicubic splines and Hayes [2] for normalised B-
          splines).

          2.4. General Linear and Nonlinear Fitting Functions

          We have indicated earlier that, unless the data-fitting
          application under consideration specifically requires some other
          type of fitting function, a polynomial or a spline is usually to
          be preferred. Special routines for these functions, in one and in
          two variables, are provided in this chapter. When the application
          does specify some other fitting function, however, it may be
          treated by a routine which deals with a general linear function,
          or by one for a general nonlinear function, depending on whether
          the coefficients in the given function occur linearly or
          nonlinearly.

          The general linear fitting function can be written in the form

                f(x)==c (phi) (x)+c (phi) (x)+...+c (phi) (x),         (15)
                       1     1     2     2         p     p

          where x is a vector of one or more independent variables, and the
          (phi)  are any given functions of these variables (though they
               i
          must be linearly independent of one another if there is to be the
          possibility of a unique solution to the fitting problem). This is
          not intended to imply that each (phi)  is necessarily a function
                                               i
          of all the variables: we may have, for example, that each (phi)
                                                                         i
          is a function of a different single variable, and even that one
          of the (phi)  is a constant. All that is required is that a value
                      i
          of each (phi) (x) can be computed when a value of each
                       i
          independent variable is given.

          When the fitting function f(x) is not linear in its coefficients,
          no more specific representation is available in general than f(x)
          itself. However, we shall find it helpful later on to indicate
          the fact that f(x) contains a number of coefficients (to be
          determined by the fitting process) by using instead the notation
          f(x;c), where c denotes the vector of coefficients. An example of
          a nonlinear fitting function is


                      f(x;c)==c +c exp(-c x)+c exp(-c x),              (16)
                               1  2      4    3      5

          which is in one variable and contains five coefficients. Note
          that here, as elsewhere in this Chapter Introduction, we use the
          term 'coefficients' to include all the quantities whose values
          are to be determined by the fitting process, not just those which
          occur linearly. We may observe that it is only the presence of
          the coefficients c  and c  which makes the form (16) nonlinear.
                            4      5
          If the values of these two coefficients were known beforehand,
          (16) would instead be a linear function which, in terms of the
          general linear form (15), has p=3 and

           (phi) (x)==1,  (phi) (x)==exp(-c x), and (phi) (x)==exp(-c x).
                1              2           4             3           5

          We may note also that polynomials and splines, such as (9) and
          (14), are themselves linear in their coefficients. Thus if, when
          fitting with these functions, a suitable special routine is not
          available (as when more than two independent variables are
          involved or when fitting in the l  norm), it is appropriate to
                                           1
          use a routine designed for a general linear function.

          2.5. Constrained Problems

          So far, we have considered only fitting processes in which the
          values of the coefficients in the fitting function are determined
          by an unconstrained minimization of a particular norm. Some
          fitting problems, however, require that further restrictions be
          placed on the determination of the coefficient values. Sometimes
          these restrictions are contained explicitly in the formulation of
          the problem in the form of equalities or inequalities which the
          coefficients, or some function of them, must satisfy. For
          example, if the fitting function contains a term Aexp(-kx), it
          may be required that k>=0. Often, however, the equality or
          inequality constraints relate to the value of the fitting
          function or its derivatives at specified values of the
          independent variable(s), but these too can be expressed in terms
          of the coefficients of the fitting function, and it is
          appropriate to do this if a general linear or nonlinear routine
          is being used. For example, if the fitting function is that given
          in (10), the requirement that the first derivative of the
          function at x=x  be non-negative can be expressed as
                         0

                     c N '(x )+c N '(x )+...+c N '(x )>=0,             (17)
                      1 1   0   2 2   0       p p   0

          where the prime denotes differentiation with respect to x and
          each derivative is evaluated at x=x . On the other hand, if the
                                             0
          requirement had been that the derivative at x=x  be exactly zero,
                                                         0
          the inequality sign in (17) would be replaced by an equality.

          Routines which provide a facility for minimizing the appropriate
          norm subject to such constraints are discussed in Section 3.6.

          2.6. References

          [1]   Cox M G and Hayes J G (1973) Curve fitting: a guide and
                suite of algorithms for the non-specialist user. Report
                NAC26. National Physical Laboratory.

          [2]   Hayes J G (1974 ) Numerical Methods for Curve and Surface
                Fitting. Bull Inst Math Appl. 10 144--152.

                (For definition of normalised B-splines and details of
                numerical methods.)

          [3]   Hayes J G (1970) Curve Fitting by Polynomials in One
                Variable. Numerical Approximation to Functions and Data. (ed
                J G Hayes) Athlone Press, London.

          [4]   Hayes J G and Halliday J (1974) The Least-squares Fitting of
                Cubic Spline Surfaces to General Data Sets. J. Inst. Math.
                Appl. 14 89--103.

          3. Recommendations on Choice and Use of Routines

          3.1. General

          The choice of a routine to treat a particular fitting problem
          will depend first of all on the fitting function and the norm to
          be used. Unless there is good reason to the contrary, the fitting
          function should be a polynomial or a cubic spline (in the
          appropriate number of variables) and the norm should be the l
                                                                       2
          norm (leading to the least-squares fit). If some other function
          is to be used, the choice of routine will depend on whether the
          function is nonlinear (in which case see Section 3.5.2) or linear
          in its coefficients (see Section 3.5.1), and, in the latter case,
          on whether the l  or l  norm is to be used. The latter section is
                          1     2
          appropriate for polynomials and splines, too, if the l  norm is
                                                                1
          preferred.

          In the case of a polynomial or cubic spline, if there is only one
          independent variable, the user should choose a spline (Section
          3.3) when the curve represented by the data is of complicated
          form, perhaps with several peaks and troughs. When the curve is
          of simple form, first try a polynomial (see Section 3.2) of low
          degree, say up to degree 5 or 6, and then a spline if the
          polynomial fails to provide a satisfactory fit. (Of course, if
          third-derivative discontinuities are unacceptable to the user, a
          polynomial is the only choice.) If the problem is one of surface
          fitting, one of the spline routines should be used (Section 3.4).
          If the problem has more than two independent variables, it may be
          treated by the general linear routine in Section 3.5.1, again
          using a polynomial in the first instance.

          Another factor which affects the choice of routine is the
          presence of constraints, as previously discussed in Section 2.5.
          Indeed this factor is likely to be overriding at present, because
          of the limited number of routines which have the necessary
          facility. See Section 3.6.

          3.1.1.  Data considerations

          A satisfactory fit cannot be expected by any means if the number
          and arrangement of the data points do not adequately represent
          the character of the underlying relationship: sharp changes in
          behaviour, in particular, such as sharp peaks, should be well
          covered. Data points should extend over the whole range of
          interest of the independent variable(s): extrapolation outside
          the data ranges is most unwise. Then, with polynomials, it is
          advantageous to have additional points near the ends of the
          ranges, to counteract the tendency of polynomials to develop
          fluctuations in these regions. When, with polynomial curves, the
          user can precisely choose the x-values of the data, the special
          points defined in Section 3.2.2 should be selected. With splines
          the choice is less critical as long as the character of the
          relationship is adequately represented. All fits should be tested
          graphically before accepting them as satisfactory.

          For this purpose it should be noted that it is not sufficient to
          plot the values of the fitted function only at the data values of
          the independent variable(s); at the least, its values at a
          similar number of intermediate points should also be plotted, as
          unwanted fluctuations may otherwise go undetected. Such
          fluctuations are the less likely to occur the lower the number of
          coefficients chosen in the fitting function. No firm guide can be
          given, but as a rough rule, at least initially, the number of
          coefficients should not exceed half the number of data points
          (points with equal or nearly equal values of the independent
          variable, or both independent variables in surface fitting,
          counting as a single point for this purpose). However, the
          situation may be such, particularly with a small number of data
          points, that a satisfactorily close fit to the data cannot be
          achieved without unwanted fluctuations occurring. In such cases,
          it is often possible to improve the situation by a transformation
          of one or more of the variables, as discussed in the next
          paragraph: otherwise it will be necessary to provide extra data
          points. Further advice on curve fitting is given in Cox and Hayes
          [1] and, for polynomials only, in Hayes [3] of Section 2.7. Much
          of the advice applies also to surface fitting; see also the
          Routine Documents.

          3.1.2.  Transformation of variables

          Before starting the fitting, consideration should be given to the
          choice of a good form in which to deal with each of the
          variables: often it will be satisfactory to use the variables as
          they stand, but sometimes the use of the logarithm, square root,
          or some other function of a variable will lead to a better-
          behaved relationship. This question is customarily taken into
          account in preparing graphs and tables of a relationship and the
          same considerations apply when curve or surface fitting. The
          practical context will often give a guide. In general, it is best
          to avoid having to deal with a relationship whose behaviour in
          one region is radically different from that in another. A steep
          rise at the left-hand end of a curve, for example, can often best
          be treated by curve fitting in terms of log(x+c) with some
          suitable value of the constant c. A case when such a
          transformation gave substantial benefit is discussed in Hayes [3]
          page 60. According to the features exhibited in any particular
          case, transformation of either dependent variable or independent
          variable(s) or both may be beneficial. When there is a choice it
          is usually better to transform the independent variable(s): if
          the dependent variable is transformed, the weights attached to
          the data points must be adjusted. Thus (denoting the dependent
          variable by y, as in the notation for curves) if the y  to be
                                                                r
          fitted have been obtained by a transformation y=g(Y) from
          original data values Y , with weights W , for r=1,2,...,m, we
                                r                r
          must take

                                w =W /(dy/dY),                         (18)
                                 r  r

          where the derivative is evaluated at Y . Strictly, the
                                                r
          transformation of Y and the adjustment of weights are valid only
          when the data errors in the Y  are small compared with the range
                                       r
          spanned by the Y , but this is usually the case.
                          r

          3.2. Polynomial Curves

          3.2.1.  Least-squares polynomials: arbitrary data points

          E02ADF fits to arbitrary data points, with arbitrary weights,
          polynomials of all degrees up to a maximum degree k, which is at
          choice. If the user is seeking only a low degree polynomial, up
          to degree 5 or 6 say, k=10 is an appropriate value, providing
          there are about 20 data points or more. To assist in deciding the
          degree of polynomial which satisfactorily fits the data, the
          routine provides the root-mean-square-residual s  for all degrees
                                                          i
          i=1,2,...,k. In a satisfactory case, these s  will decrease
                                                      i
          steadily as i increases and then settle down to a fairly constant
          value, as shown in the example

                  i    s
                        i

                  0    3.5215

                  1    0.7708

                  2    0.1861

                  3    0.0820

                  4    0.0554

                  5    0.0251

                  6    0.0264

                  7    0.0280

                  8    0.0277

                  9    0.0297

                  10   0.0271

          If the s  values settle down in this way, it indicates that the
                  i
          closest polynomial approximation justified by the data has been
          achieved. The degree which first gives the approximately constant
          value of s  (degree 5 in the example) is the appropriate degree
                    i
          to select. (Users who are prepared to accept a fit higher than
          sixth degree, should simply find a high enough value of k to
          enable the type of behaviour indicated by the example to be
          detected: thus they should seek values of k for which at least 4
          or 5 consecutive values of s  are approximately the same.) If the
                                      i
          degree were allowed to go high enough, s  would, in most cases,
                                                  i
          eventually start to decrease again, indicating that the data
          points are being fitted too closely and that undesirable
          fluctuations are developing between the points. In some cases,
          particularly with a small number of data points, this final
          decrease is not distinguishable from the initial decrease in s .
                                                                        i
          In such cases, users may seek an acceptable fit by examining the
          graphs of several of the polynomials obtained. Failing this, they
          may (a) seek a transformation of variables which improves the
          behaviour, (b) try fitting a spline, or (c) provide more data
          points. If data can be provided simply by drawing an
          approximating curve by hand and reading points from it, use the
          points discussed in Section 3.2.2.

          3.2.2.  Least-squares polynomials: selected data points

          When users are at liberty to choose the x-values of data points,
          such as when the points are taken from a graph, it is most
          advantageous when fitting with polynomials to use the values
          x =cos((pi)r/n), for r=0,1,...,n for some value of n, a suitable
           r
          value for which is discussed at the end of this section. Note
          that these x  relate to the variable x after it has been
                      r
          normalised so that its range of interest is -1 to +1. E02ADF may
          then be used as in Section 3.2.1 to seek a satisfactory fit.

          3.3. Cubic Spline Curves

          3.3.1.  Least-squares cubic splines

          E02BAF fits to arbitrary data points, with arbitrary weights, a
          cubic spline with interior knots specified by the user. The
          choice of these knots so as to give an acceptable fit must
          largely be a matter of trial and error, though with a little
          experience a satisfactory choice can often be made after one or
          two trials. It is usually best to start with a small number of
          knots (too many will result in unwanted fluctuations in the fit,
          or even in there being no unique solution) and, examining the fit
          graphically at each stage, to add a few knots at a time at places
          where the fit is particularly poor. Moving the existing knots
          towards these places will also often improve the fit. In regions
          where the behaviour of the curve underlying the data is changing
          rapidly, closer knots will be needed than elsewhere. Otherwise,
          positioning is not usually very critical and equally-spaced knots
          are often satisfactory. See also the next section, however.

          A useful feature of the routine is that it can be used in
          applications which require the continuity to be less than the
          normal continuity of the cubic spline. For example, the fit may
          be required to have a discontinuous slope at some point in the
          range. This can be achieved by placing three coincident knots at
          the given point. Similarly a discontinuity in the second
          derivative at a point can be achieved by placing two knots there.
          Analogy with these discontinuous cases can provide guidance in
          more usual cases: for example, just as three coincident knots can
          produce a discontinuity in slope, so three close knots can
          produce a rapid change in slope. The closer the knots are, the
          more rapid can the change be.

                                     Figure 1
                   Please see figure in printed Reference Manual

          An example set of data is given in Figure 1. It is a rather
          tricky set, because of the scarcity of data on the right, but it
          will serve to illustrate some of the above points and to show
          some of the dangers to be avoided. Three interior knots
          (indicated by the vertical lines at the top of the diagram) are
          chosen as a start. We see that the resulting curve is not steep
          enough in the middle and fluctuates at both ends, severely on the
          right. The spline is unable to cope with the shape and more knots
          are needed.

          In Figure 2, three knots have been added in the centre, where the
          data shows a rapid change in behaviour, and one further out at
          each end, where the fit is poor. The fit is still poor, so a
          further knot is added in this region and, in Figure 3, disaster
          ensues in rather spectacular fashion.

                                     Figure 2
                   Please see figure in printed Reference Manual

                                     Figure 3
                   Please see figure in printed Reference Manual

          The reason is that, at the right-hand end, the fits in Figure 1
          and Figure 2 have been interpreted as poor simply because of the
          fluctuations about the curve underlying the data (or what it is
          naturally assumed to be). But the fitting process knows only
          about the data and nothing else about the underlying curve, so it
          is important to consider only closeness to the data when deciding
          goodness of fit.

          Thus, in Figure 1, the curve fits the last two data points quite
          well compared with the fit elsewhere, so no knot should have been
          added in this region. In Figure 2, the curve goes exactly through
          the last two points, so a further knot is certainly not needed
          here.


                                     Figure 4
                   Please see figure in printed Reference Manual

          Figure 4 shows what can be achieved without the extra knot on
          each of the flat regions. Remembering that within each knot
          interval the spline is a cubic polynomial, there is really no
          need to have more than one knot interval covering each flat
          region.

          What we have, in fact, in Figure 2 and Figure 3 is a case of too
          many knots (so too many coefficients in the spline equation) for
          the number of data points. The warning in the second paragraph of
          Section 2.1 was that the fit will then be too close to the data,
          tending to have unwanted fluctuations between the data points.
          The warning applies locally for splines, in the sense that, in
          localities where there are plenty of data points, there can be a
          lot of knots, as long as there are few knots where there are few
          points, especially near the ends of the interval. In the present
          example, with so few data points on the right, just the one extra
          knot in Figure 2 is too many! The signs are clearly present, with
          the last two points fitted exactly (at least to the graphical
          accuracy and actually much closer than that) and fluctuations
          within the last two knot-intervals (cf. Figure 1, where only the
          final point is fitted exactly and one of the wobbles spans
          several data points).

          The situation in Figure 3 is different. The fit, if computed
          exactly, would still pass through the last two data points, with
          even more violent fluctuations. However, the problem has become
          so ill-conditioned that all accuracy has been lost. Indeed, if
          the last interior knot were moved a tiny amount to the right,
          there would be no unique solution and an error message would have
          been caused. Near-singularity is, sadly, not picked up by the
          routine, but can be spotted readily in a graph, as Figure 3. B-
          spline coefficients becoming large, with alternating signs, is
          another indication. However, it is better to avoid such
          situations, firstly by providing, whenever possible, data
          adequately covering the range of interest, and secondly by
          placing knots only where there is a reasonable amount of data.

          The example here could, in fact, have utilised from the start the
          observation made in the second paragraph of this section, that
          three close knots can produce a rapid change in slope. The
          example has two such rapid changes and so requires two sets of
          three close knots (in fact, the two sets can be so close that one
          knot can serve in both sets, so only five knots prove sufficient
          in Figure 4). It should be noted, however, that the rapid turn
          occurs within the range spanned by the three knots. This is the
          reason that the six knots in Figure 2 are not satisfactory as
          they do not quite span the two turns.

          Some more examples to illustrate the choice of knots are given in
          Cox and Hayes [1].

          3.3.2.  Automatic fitting with cubic splines

          E02BEF also fits cubic splines to arbitrary data points with
          arbitrary weights but itself chooses the number and positions of
          the knots. The user has to supply only a threshold for the sum of
          squares of residuals. The routine first builds up a knot set by a
          series of trial fits in the l  norm. Then, with the knot set
                                       2
          decided, the final spline is computed to minimize a certain
          smoothing measure subject to satisfaction of the chosen
          threshold. Thus it is easier to use than E02BAF (see previous
          section), requiring only some experimentation with this
          threshold. It should therefore be first choice unless the user
          has a preference for the ordinary least-squares fit or, for
          example, wishes to experiment with knot positions, trying to keep
          their number down (E02BEF aims only to be reasonably frugal with
          knots).

          3.4. Spline Surfaces

          3.4.1.  Least-squares bicubic splines

          E02DAF fits to arbitrary data points, with arbitrary weights, a
          bicubic spline with its two sets of interior knots specified by
          the user. For choosing these knots, the advice given for cubic
          splines, in Section 3.3.1 above, applies here too. (See also the
          next section, however.) If changes in the behaviour of the
          surface underlying the data are more marked in the direction of
          one variable than of the other, more knots will be needed for the
          former variable than the latter. Note also that, in the surface
          case, the reduction in continuity caused by coincident knots will
          extend across the whole spline surface: for example, if three
          knots associated with the variable x are chosen to coincide at a
          value L, the spline surface will have a discontinuous slope
          across the whole extent of the line x=L.

          With some sets of data and some choices of knots, the least-
          squares bicubic spline will not be unique. This will not occur,
          with a reasonable choice of knots, if the rectangle R is well
          covered with data points: here R is defined as the smallest
          rectangle in the (x,y) plane, with sides parallel to the axes,
          which contains all the data points. Where the least-squares
          solution is not unique, the minimal least-squares solution is
          computed, namely that least-squares solution which has the
          smallest value of the sum of squares of the B-spline coefficients
          c   (see the end of Section 2.3.2 above). This choice of least-
           ij
          squares solution tends to minimize the risk of unwanted
          fluctuations in the fit. The fit will not be reliable, however,
          in regions where there are few or no data points.

          3.4.2.  Automatic fitting with bicubic splines

          E02DDF also fits bicubic splines to arbitrary data points with
          arbitrary weights but chooses the knot sets itself. The user has
          to supply only a threshold for the sum of squares of residuals.
          Just like the automatic curve E02BEF (Section 3.3.2), E02DDF then
          builds up the knot sets and finally fits a spline minimizing a
          smoothing measure subject to satisfaction of the threshold.
          Again, this easier to use routine is normally to be preferred, at
          least in the first instance.

          E02DCF is a very similar routine to E02DDF but deals with data
          points of equal weight which lie on a rectangular mesh in the
          (x,y) plane. This kind of data allows a very much faster
          computation and so is to be preferred when applicable.
          Substantial departures from equal weighting can be ignored if the
          user is not concerned with statistical questions, though the
          quality of the fit will suffer if this is taken too far. In such
          cases, the user should revert to E02DDF.

          3.5. General Linear and Nonlinear Fitting Functions

          3.5.1.  General linear functions

          For the general linear function (15), routines are available for
          fitting in the l  and l  norms. The least-squares routines (which
                          1      2
          are to be preferred unless there is good reason to use another
          norm -- see Section 2.1.1) are in Chapter F04. The l  routine is
                                                              1
          E02GAF.

          All the above routines are essentially linear algebra routines,
          and in considering their use we need to view the fitting process
          in a slightly different way from hitherto. Taking y to be the
          dependent variable and x the vector of independent variables, we
          have, as for equation (1) but with each x  now a vector,
                                                   r

                          (epsilon) =y -f(x )  r=1,2,...,m.
                                   r  r    r

          Substituting for f(x) the general linear form (15), we can write
          this as

          c (phi) (x )+c (phi) (x )+...+c (phi) (x )=y -(epsilon) ,
           1     1  r   2     2  r       p     p  r   r          r
           r=1,2,...,m                                                 (19)


          Thus we have a system of linear equations in the coefficients c .
                                                                         j
          Usually, in writing these equations, the (epsilon)  are omitted
                                                            r
          and simply taken as implied. The system of equations is then
          described as an overdetermined system (since we must have m>=p if
          there is to be the possibility of a unique solution to our
          fitting problem), and the fitting process of computing the c  to
                                                                      j
          minimize one or other of the norms (2), (3) and (4) can be
          described, in relation to the system of equations, as solving the
          overdetermined system in that particular norm. In matrix
          notation, the system can be written as

                                   (Phi)c=y,                           (20)

          where (Phi) is the m by p matrix whose element in row r and
          column j is (phi) (x ), for r=1,2,...,m; j=1,2,...,p. The vectors
                           j  r
          c and y respectively contain the coefficients c  and the data
                                                         j
          values y .
                  r

          The routines, however, use the standard notation of linear
          algebra, the overdetermined system of equations being denoted by

                                     Ax=b                              (21)

          The correspondence between this notation and that which we have
          used for the data-fitting problem (equation (20)) is therefore
          given by

                            A==(Phi),   x==c   b==y                    (22)

          Note that the norms used by these routines are the unweighted
          norms (2) and (3). If the user wishes to apply weights to the
          data points, that is to use the norms (5) or (6), the
          equivalences (22) should be replaced by

                              A==D(Phi),   x==c   b==Dy

          where D is a diagonal matrix with w  as the rth diagonal element.
                                             r
          Here w , for r=1,2,...,m, is the weight of the rth data point as
                r
          defined in Section 2.1.2.

          3.5.2.  Nonlinear functions

          Routines for fitting with a nonlinear function in the l  norm are
                                                                 2
          provided in Chapter E04, and that chapter's Introduction should
          be consulted for the appropriate choice of routine. Again,
          however, the notation adopted is different from that we have used
          for data fitting. In the latter, we denote the fitting function
          by f(x;c), where x is the vector of independent variables and c
          is the vector of coefficients, whose values are to be determined.
          The squared l  norm, to be minimized with respect to the elements
                       2
          of c, is then

                               m
                               --  2            2
                               >  w [y -f(x ;c)]                       (23)
                               --  r  r    r
                               r=1

          where y  is the rth data value of the dependent variable, x  is
                 r                                                   r
          the vector containing the rth values of the independent
          variables, and w  is the corresponding weight as defined in
                          r
          Section 2.1.2.

          On the other hand, in the nonlinear least-squares routines of
          Chapter E04, the function to be minimized is denoted by

                                   m
                                   --  2
                                   >  f (x),                           (24)
                                   --  i
                                   i=1

          the minimization being carried out with respect to the elements
          of the vector x. The correspondence between the two notations is
          given by

          x==c and

          f (x)==w [y -f(x ;c)],  i=r=1,2,...,m.
           i      r  r    r

          Note especially that the vector x of variables of the nonlinear
          least-squares routines is the vector c of coefficients of the
          data-fitting problem, and in particular that, if the selected
          routine requires derivatives of the f (x) to be provided, these
                                               i
          are derivatives of w [y -f(x ;c)] with respect to the
                              r  r    r
          coefficients of the data-fitting problem.

          3.6. Constraints

          At present, there are only a limited number of routines which fit
          subject to constraints. Chapter E04 contains a routine, E04UCF,
          which can be used for fitting with a nonlinear function in the l
                                                                          2
          norm subject to equality or inequality constraints. This routine,
          unlike those in that chapter suited to the unconstrained case, is
          not designed specifically for minimizing functions which are sums
          of squares, and so the function (23) has to be treated as a
          general nonlinear function. The E04 Chapter Introduction should
          be consulted.

          The remaining constraint routine relates to fitting with
          polynomials in the l  norm. E02AGF deals with polynomial curves
                              2
          and allows precise values of the fitting function and (if
          required) all its derivatives up to a given order to be
          prescribed at one or more values of the independent variable.

          3.7. Evaluation, Differentiation and Integration

          Routines are available to evaluate, differentiate and integrate
          polynomials in Chebyshev-series form and cubic or bicubic splines
          in B-spline form. These polynomials and splines may have been
          produced by the various fitting routines or, in the case of
          polynomials, from prior calls of the differentiation and
          integration routines themselves.

          E02AEF and E02AKF evaluate polynomial curves: the latter has a
          longer parameter list but does not require the user to normalise
          the values of the independent variable and can accept
          coefficients which are not stored in contiguous locations. E02BBF
          evaluates cubic spline curves, and E02DEF and E02DFF bicubic
          spline surfaces.

          Differentiation and integration of polynomial curves are carried
          out by E02AHF and E02AJF respectively. The results are provided
          in Chebyshev-series form and so repeated differentiation and
          integration are catered for. Values of the derivative or integral
          can then be computed using the appropriate evaluation routine.

          For splines the differentiation and integration routines provided
          are of a different nature from those for polynomials. E02BCF
          provides values of a cubic spline curve and its first three
          derivatives (the rest, of course, are zero) at a given value of x
          spline over its whole range. These routines can also be applied
          to surfaces of the form (14). For example, if, for each value of
          j in turn, the coefficients c  , for i=1,2,...,p are supplied to
                                       ij
          E02BCF with x=x  and on each occasion we select from the output
                         0
          the value of the second derivative, d  say, and if the whole set
                                               j
          of d  are then supplied to the same routine with x=y , the output
              j                                               0
          will contain all the values at (x ,y ) of
                                           0  0

                             2             r+2
                           dd f          dd   f
                           -----  and   --------,  r=1,2,3.
                             2             2   r
                           dd fx        ddx ddy

          Equally, if after each of the first p calls of E02BCF we had
          selected the function value (E02BBF would also provide this)
          instead of the second derivative and we had supplied these values
          to E02BDF, the result obtained would have been the value of

                                     B
                                     /
                                     |f(x ,y)dy,
                                     /   0
                                     A

          where A and B are the end-points of the y interval over which the
          spline was defined.

          3.8. Index

          Automatic fitting,
               with bicubic splines                                  E02DCF
                                                                     E02DDF
               with cubic splines                                    E02BEF
          Data on rectangular mesh                                   E02DCF
          Differentiation,
               of cubic splines                                      E02BCF
               of polynomials                                        E02AHF
          Evaluation,
               of bicubic splines                                    E02DEF
                                                                     E02DFF
               of cubic splines                                      E02BBF
               of cubic splines and derivatives                      E02BCF
               of definite integral of cubic splines                 E02BDF
               of polynomials                                        E02AEF
                                                                     E02AKF
          Integration,
               of cubic splines (definite integral)                  E02BDF
               of polynomials                                        E02AJF
          Least-squares curve fit,
               with cubic splines                                    E02BAF
               with polynomials,
                    arbitrary data points                            E02ADF
                    with constraints                                 E02AGF
          Least-squares surface fit with bicubic splines             E02DAF
          l  fit with general linear function,                       E02GAF
           1
          Sorting,
               2-D data into panels                                  E02ZAF


          E02 -- Curve and Surface Fitting                  Contents -- E02
          Chapter E02

          Curve and Surface Fitting

          E02ADF  Least-squares curve fit, by polynomials, arbitrary data
                  points

          E02AEF  Evaluation of fitted polynomial in one variable from
                  Chebyshev series form (simplified parameter list)

          E02AGF  Least-squares polynomial fit, values and derivatives may
                  be constrained, arbitrary data points,

          E02AHF  Derivative of fitted polynomial in Chebyshev series form

          E02AJF  Integral of fitted polynomial in Chebyshev series form

          E02AKF  Evaluation of fitted polynomial in one variable, from
                  Chebyshev series form

          E02BAF  Least-squares curve cubic spline fit (including
                  interpolation)

          E02BBF  Evaluation of fitted cubic spline, function only

          E02BCF  Evaluation of fitted cubic spline, function and
                  derivatives

          E02BDF  Evaluation of fitted cubic spline, definite integral

          E02BEF  Least-squares cubic spline curve fit, automatic knot
                  placement

          E02DAF  Least-squares surface fit, bicubic splines

          E02DCF  Least-squares surface fit by bicubic splines with
                  automatic knot placement, data on rectangular grid

          E02DDF  Least-squares surface fit by bicubic splines with
                  automatic knot placement, scattered data

          E02DEF  Evaluation of a fitted bicubic spline at a vector of
                  points

          E02DFF  Evaluation of a fitted bicubic spline at a mesh of points

          E02GAF  L -approximation by general linear function
                   1

          E02ZAF  Sort 2-D data into panels for fitting bicubic splines

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02ADF
                  E02ADF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02ADF computes weighted least-squares polynomial approximations
          to an arbitrary set of data points.

          2. Specification

                 SUBROUTINE E02ADF (M, KPLUS1, NROWS, X, Y, W, WORK1,
                1                   WORK2, A, S, IFAIL)
                 INTEGER          M, KPLUS1, NROWS, IFAIL
                 DOUBLE PRECISION X(M), Y(M), W(M), WORK1(3*M), WORK2
                1                 (2*KPLUS1), A(NROWS,KPLUS1), S(KPLUS1)

          3. Description

          This routine determines least-squares polynomial approximations
          of degrees 0,1,...,k to the set of data points (x ,y ) with
                                                           r  r
          weights w , for r=1,2,...,m.
                   r

          The approximation of degree i has the property that it minimizes
          (sigma)  the sum of squares of the weighted residuals (epsilon) ,
                 i                                                       r
          where

                                (epsilon) =w (y -f )
                                         r  r  r  r

          and f  is the value of the polynomial of degree i at the rth data
               r
          point.

          Each polynomial is represented in Chebyshev-series form with
                              

          normalised argument x. This argument lies in the range -1 to +1
          and is related to the original variable x by the linear
          transformation

                                    (2x-x   -x   )
                                         max  min
                                 x= --------------.
                                     (x   -x   )
                                       max  min

          Here x    and x    are respectively the largest and smallest
                max      min
          values of x . The polynomial approximation of degree i is
                     r
          represented as

               1                                                   
               -a     T (x)+a     T (x)+a     T (x)+...+a       T (x),
               2 i+1,1 0     i+1,2 1     i+1,3 2         i+1,i+1 i

                   

          where T (x) is the Chebyshev polynomial of the first kind of
                 j
                                  

          degree j with argument (x).

          For i=0,1,...,k, the routine produces the values of a       , for
                                                               i+1,j+1
          j=0,1,...,i, together with the value of the root mean square
                           

                          / (sigma)
                         /         i
          residual s =  /   --------. In the case m=i+1 the routine sets
                    i \/     m-i-1
          the value of s  to zero.
                        i

          The method employed is due to Forsythe [4] and is based upon the
          generation of a set of polynomials orthogonal with respect to
          summation over the normalised data set. The extensions due to
          Clenshaw [1] to represent these polynomials as well as the
          approximating polynomials in their Chebyshev-series forms are
          incorporated. The modifications suggested by Reinsch and
          Gentleman (see [5]) to the method originally employed by Clenshaw
          for evaluating the orthogonal polynomials from their Chebyshev-
          series representations are used to give greater numerical
          stability.

          For further details of the algorithm and its use see Cox [2] and
          [3].

          Subsequent evaluation of the Chebyshev-series representations of
          the polynomial approximations should be carried out using E02AEF.

          4. References

          [1]   Clenshaw C W (1960) Curve Fitting with a Digital Computer.
                Comput. J. 2 170--173.

          [2]   Cox M G (1974) A Data-fitting Package for the Non-specialist
                User. Software for Numerical Mathematics. (ed D J Evans)
                Academic Press.

          [3]   Cox M G and Hayes J G (1973) Curve fitting: a guide and
                suite of algorithms for the non-specialist user. Report
                NAC26. National Physical Laboratory.

          [4]   Forsythe G E (1957) Generation and use of orthogonal
                polynomials for data fitting with a digital computer. J.
                Soc. Indust. Appl. Math. 5 74--88.

          [5]   Gentlemen W M (1969) An Error Analysis of Goertzel's
                (Watt's) Method for Computing Fourier Coefficients. Comput.
                J. 12 160--165.

          [6]   Hayes J G (1970) Curve Fitting by Polynomials in One
                Variable. Numerical Approximation to Functions and Data. (ed
                J G Hayes) Athlone Press, London.

          5. Parameters

           1:  M -- INTEGER                                           Input
               On entry: the number m of data points. Constraint: M >=
               MDIST >= 2, where MDIST is the number of distinct x values
               in the data.

           2:  KPLUS1 -- INTEGER                                      Input
               On entry: k+1, where k is the maximum degree required.
               Constraint: 0 < KPLUS1 <= MDIST, where MDIST is the number
               of distinct x values in the data.

           3:  NROWS -- INTEGER                                       Input
               On entry:
               the first dimension of the array A as declared in the
               (sub)program from which E02ADF is called.
               Constraint: NROWS >= KPLUS1.

           4:  X(M) -- DOUBLE PRECISION array                         Input
               On entry: the values x  of the independent variable, for
                                     r
               r=1,2,...,m. Constraint: the values must be supplied in non-
               decreasing order with X(M) > X(1).

           5:  Y(M) -- DOUBLE PRECISION array                         Input
               On entry: the values y  of the dependent variable, for
                                     r
               r=1,2,...,m.

           6:  W(M) -- DOUBLE PRECISION array                         Input
               On entry: the set of weights, w , for r=1,2,...,m. For
                                              r
               advice on the choice of weights, see Section 2.1.2 of the
               Chapter Introduction. Constraint: W(r) > 0.0, for r=1,2,...m.

           7:  WORK1(3*M) -- DOUBLE PRECISION array               Workspace

           8:  WORK2(2*KPLUS1) -- DOUBLE PRECISION array          Workspace

           9:  A(NROWS,KPLUS1) -- DOUBLE PRECISION array             Output
                                                

               On exit: the coefficients of T (x) in the approximating
                                             j
               polynomial of degree i. A(i+1,j+1) contains the coefficient
               a       , for i=0,1,...,k; j=0,1,...,i.
                i+1,j+1

          10:  S(KPLUS1) -- DOUBLE PRECISION array                   Output
               On exit: S(i+1) contains the root mean square residual s ,
                                                                       i
               for i=0,1,...,k, as described in Section 3. For the
               interpretation of the values of the s  and their use in
                                                    i
               selecting an appropriate degree, see Section 3.1 of the
               Chapter Introduction.

          11:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               The weights are not all strictly positive.

          IFAIL= 2
               The values of X(r), for r=1,2,...,M are not in non-
               decreasing order.

          IFAIL= 3
               All X(r) have the same value: thus the normalisation of X is
               not possible.

          IFAIL= 4
               On entry KPLUS1 < 1 (so the maximum degree required is
                        negative)

               or       KPLUS1 > MDIST, where MDIST is the number of
                        distinct x values in the data (so there cannot be a
                        unique solution for degree k=KPLUS1-1).

          IFAIL= 5
               NROWS < KPLUS1.

          7. Accuracy

          No error analysis for the method has been published. Practical
          experience with the method, however, is generally extremely
          satisfactory.

          8. Further Comments

          The time taken by the routine is approximately proportional to
          m(k+1)(k+11).

          The approximating polynomials may exhibit undesirable
          oscillations (particularly near the ends of the range) if the
          maximum degree k exceeds a critical value which depends on the
          number of data points m and their relative positions. As a rough
          guide, for equally-spaced data, this critical value is about
              

          2*\/m. For further details see Hayes [6] page 60.

          9. Example

          Determine weighted least-squares polynomial approximations of
          degrees 0, 1, 2 and 3 to a set of 11 prescribed data points. For
          the approximation of degree 3, tabulate the data and the
          corresponding values of the approximating polynomial, together
          with the residual errors, and also the values of the
          approximating polynomial at points half-way between each pair of
          adjacent data points.

          The example program supplied is written in a general form that
          will enable polynomial approximations of degrees 0,1,...,k to be
          obtained to m data points, with arbitrary positive weights, and
          the approximation of degree k to be tabulated. E02AEF is used to
          evaluate the approximating polynomial. The program is self-
          starting in that any number of data sets can be supplied.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02AEF
                  E02AEF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02AEF evaluates a polynomial from its Chebyshev-series
          representation.

          2. Specification

                 SUBROUTINE E02AEF (NPLUS1, A, XCAP, P, IFAIL)
                 INTEGER          NPLUS1, IFAIL
                 DOUBLE PRECISION A(NPLUS1), XCAP, P

          3. Description

          This routine evaluates the polynomial

                        1                                   
                        -a T (x)+a T (x)+a T (x)+...+a   T (x)
                        2 1 0     2 1     3 2         n+1 n

                                                          

          for any value of x satisfying -1<=x<=1. Here T (x) denotes the
                                                        j
          Chebyshev polynomial of the first kind of degree j with argument
          

          x. The value of n is prescribed by the user.

                                    

          In practice, the variable x will usually have been obtained from
          an original variable x, where x   <=x<=x    and
                                         min      max

                                  ((x-x   )-(x   -x))
                                       min    max
                               x= -------------------
                                      (x   -x   )
                                        max  min

          Note that this form of the transformation should be used
          computationally rather than the mathematical equivalent

                                     (2x-x   -x   )
                                          min  max
                                  x= --------------
                                      (x   -x   )
                                        max  min

                                                                 

          since the former guarantees that the computed value of x differs
          from its true value by at most 4(epsilon), where (epsilon) is the
          machine precision, whereas the latter has no such guarantee.

          The method employed is based upon the three-term recurrence
          relation due to Clenshaw [1], with modifications to give greater
          numerical stability due to Reinsch and Gentleman (see [4]).

          For further details of the algorithm and its use see Cox [2] and
          [3].

          4. References

          [1]   Clenshaw C W (1955) A Note on the Summation of Chebyshev
                Series. Math. Tables Aids Comput. 9 118--120.

          [2]   Cox M G (1974) A Data-fitting Package for the Non-specialist
                User. Software for Numerical Mathematics. (ed D J Evans)
                Academic Press.

          [3]   Cox M G and Hayes J G (1973) Curve fitting: a guide and
                suite of algorithms for the non-specialist user. Report
                NAC26. National Physical Laboratory.

          [4]   Gentlemen W M (1969) An Error Analysis of Goertzel's
                (Watt's) Method for Computing Fourier Coefficients. Comput.
                J. 12 160--165.

          5. Parameters

           1:  NPLUS1 -- INTEGER                                      Input
               On entry: the number n+1 of terms in the series (i.e., one
               greater than the degree of the polynomial). Constraint:
               NPLUS1 >= 1.

           2:  A(NPLUS1) -- DOUBLE PRECISION array                    Input
               On entry: A(i) must be set to the value of the ith
               coefficient in the series, for i=1,2,...,n+1.

           3:  XCAP -- DOUBLE PRECISION                               Input
                         

               On entry: x, the argument at which the polynomial is to be
               evaluated. It should lie in the range -1 to +1, but a value
               just outside this range is permitted (see Section 6) to
               allow for possible rounding errors committed in the
                                        

               transformation from x to x discussed in Section 3. Provided
               the recommended form of the transformation is used, a
               successful exit is thus assured whenever the value of x lies
               in the range x    to x   .
                             min     max

           4:  P -- DOUBLE PRECISION                                 Output
               On exit: the value of the polynomial.

           5:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               ABS(XCAP) > 1.0 + 4(epsilon), where (epsilon) is the
               machine precision. In this case the value of P is set
               arbitrarily to zero.

          IFAIL= 2
               On entry NPLUS1 < 1.

          7. Accuracy

          The rounding errors committed are such that the computed value of
          the polynomial is exact for a slightly perturbed set of
          coefficients a +(delta)a . The ratio of the sum of the absolute
                        i         i
          values of the (delta)a  to the sum of the absolute values of the
                                i
          a  is less than a small multiple of (n+1) times machine
           i
          precision.

          8. Further Comments

          The time taken by the routine is approximately proportional to
          n+1.

          It is expected that a common use of E02AEF will be the evaluation
          of the polynomial approximations produced by E02ADF and E02AFF(*)

          9. Example

                                                                   

          Evaluate at 11 equally-spaced points in the interval -1<=x<=1 the
          polynomial of degree 4 with Chebyshev coefficients, 2.0, 0.5, 0.
          25, 0.125, 0.0625.

          The example program is written in a general form that will enable
          a polynomial of degree n in its Chebyshev-series form to be
                                                                   

          evaluated at m equally-spaced points in the interval -1<=x<=1.
          The program is self-starting in that any number of data sets can
          be supplied.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02AGF
                  E02AGF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02AGF computes constrained weighted least-squares polynomial
          approximations in Chebyshev-series form to an arbitrary set of
          data points. The values of the approximations and any number of
          their derivatives can be specified at selected points.

          2. Specification

                 SUBROUTINE E02AGF (M, KPLUS1, NROWS, XMIN, XMAX, X, Y, W,
                1                   MF, XF, YF, LYF, IP, A, S, NP1, WRK,
                2                   LWRK, IWRK, LIWRK, IFAIL)
                 INTEGER          M, KPLUS1, NROWS, MF, LYF, IP(MF), NP1,
                1                 LWRK, IWRK(LIWRK), LIWRK, IFAIL
                 DOUBLE PRECISION XMIN, XMAX, X(M), Y(M), W(M), XF(MF), YF
                1                 (LYF), A(NROWS,KPLUS1), S(KPLUS1), WRK
                2                 (LWRK)

          3. Description

          This routine determines least-squares polynomial approximations
          of degrees up to k to the set of data points (x ,y ) with weights
                                                         r  r
          w , for r=1,2,...,m. The value of k, the maximum degree required,
           r
          is prescribed by the user. At each of the values XF , for r =
                                                             r
          1,2,...,MF, of the independent variable x, the approximations and
          their derivatives up to order p  are constrained to have one of
                                         r
                                                                      MF
                                                                      --
          the user-specified values YF , for s=1,2,...,n, where n=MF+ >  p
                                      s                               --  r
                                                                      r=1

          The approximation of degree i has the property that, subject to
          the imposed contraints, it minimizes (Sigma) , the sum of the
                                                      i
          squares of the weighted residuals (epsilon)  for r=1,2,...,m
                                                     r
          where

                              (epsilon) =w (y -f (x ))
                                       r  r  r  i  r

          and f (x ) is the value of the polynomial approximation of degree
               i  r
          i at the rth data point.

          Each polynomial is represented in Chebyshev-series form with
                              

          normalised argument x. This argument lies in the range -1 to +1
          and is related to the original variable x by the linear
          transformation

                                     2x-(x   +x   )
                                          max  min
                                  x= --------------
                                      (x   -x   )
                                        max  min

          where x    and x   , specified by the user, are respectively the
                 min      max
          lower and upper end-points of the interval of x over which the
          polynomials are to be defined.

          The polynomial approximation of degree i can be written as

                      1                                      
                      -a   +a   T (x)+...+a  T (x)+...+a  T (x)
                      2 i,0  i,1 1         ij j         ii i

                   

          where T (x) is the Chebyshev polynomial of the first kind of
                 j
                                 

          degree j with argument x. For i=n,n+1,...,k, the routine produces
          the values of the coefficients a  , for j=0,1,...,i, together
                                          ij
          with the value of the root mean square residual, S , defined as
                                                            i
                 

                /     --
               /      >
              /       --
             /        i
            /     ----------, where m' is the number of data points with
          \/      (m'+n-i-1)
          non-zero weight.

          Values of the approximations may subsequently be computed using
          E02AEF or E02AKF.

                                                    

          First E02AGF determines a polynomial (mu)(x), of degree n-1,
          which satisfies the given constraints, and a polynomial (nu)(x),
          of degree n, which has value (or derivative) zero wherever a
          constrained value (or derivative) is specified. It then fits
          y -(mu)(x ), for r=1,2,...,m with polynomials of the required
           r       r
                                            

          degree in x each with factor (nu)(x). Finally the coefficients of
               

          (mu)(x) are added to the coefficients of these fits to give the
          coefficients of the constrained polynomial approximations to the
          data points (x ,y ), for r=1,2,...,m. The method employed is
                        r  r
          given in Hayes [3]: it is an extension of Forsythe's orthogonal
          polynomials method [2] as modified by Clenshaw [1].

          4. References

          [1]   Clenshaw C W (1960) Curve Fitting with a Digital Computer.
                Comput. J. 2 170--173.

          [2]   Forsythe G E (1957) Generation and use of orthogonal
                polynomials for data fitting with a digital computer. J.
                Soc. Indust. Appl. Math. 5 74--88.

          [3]   Hayes J G (1970) Curve Fitting by Polynomials in One
                Variable. Numerical Approximation to Functions and Data. (ed
                J G Hayes) Athlone Press, London.

          5. Parameters

           1:  M -- INTEGER                                           Input
               On entry: the number m of data points to be fitted.
               Constraint: M >= 1.

           2:  KPLUS1 -- INTEGER                                      Input
               On entry: k+1, where k is the maximum degree required.
               Constraint: n+1<=KPLUS1<=m''+n, where n is the total number
               of constraints and m'' is the number of data points with
               non-zero weights and distinct abscissae which do not
               coincide with any of the XF(r).

           3:  NROWS -- INTEGER                                       Input
               On entry:
               the first dimension of the array A as declared in the
               (sub)program from which E02AGF is called.
               Constraint: NROWS >= KPLUS1.

           4:  XMIN -- DOUBLE PRECISION                               Input

           5:  XMAX -- DOUBLE PRECISION                               Input
               On entry: the lower and upper end-points, respectively, of
               the interval [x   ,x   ]. Unless there are specific reasons
                              min  max
               to the contrary, it is recommended that XMIN and XMAX be set
               respectively to the lowest and highest value among the x
                                                                       r
               and XF(r). This avoids the danger of extrapolation provided
               there is a constraint point or data point with non-zero
               weight at each end-point. Constraint: XMAX > XMIN.

           6:  X(M) -- DOUBLE PRECISION array                         Input
               On entry: the value x  of the independent variable at the r
                                    r
               th data point, for r=1,2,...,m. Constraint: the X(r) must be
               in non-decreasing order and satisfy XMIN <= X(r) <= XMAX.

           7:  Y(M) -- DOUBLE PRECISION array                         Input
               On entry: Y(r) must contain y , the value of the dependent
                                            r
               variable at the rth data point, for r=1,2,...,m.

           8:  W(M) -- DOUBLE PRECISION array                         Input
               On entry: the weights w  to be applied to the data points
                                      r
               x , for r=1,2...,m. For advice on the choice of weights see
                r
               the Chapter Introduction. Negative weights are treated as
               positive. A zero weight causes the corresponding data point
               to be ignored. Zero weight should be given to any data point
               whose x and y values both coincide with those of a
               constraint (otherwise the denominators involved in the root-
               mean-square residuals s  will be slightly in error).
                                      i

           9:  MF -- INTEGER                                          Input
               On entry: the number of values of the independent variable
               at which a constraint is specified. Constraint: MF >= 1.

          10:  XF(MF) -- DOUBLE PRECISION array                       Input
               On entry: the rth value of the independent variable at
               which a constraint is specified, for r = 1,2,...,MF.
               Constraint: these values need not be ordered but must be
               distinct and satisfy XMIN <= XF(r) <= XMAX.

          11:  YF(LYF) -- DOUBLE PRECISION array                      Input
               On entry: the values which the approximating polynomials
               and their derivatives are required to take at the points
               specified in XF. For each value of XF(r), YF contains in
               successive elements the required value of the approximation,
               its first derivative, second derivative,..., p th
                                                             r
               derivative, for r = 1,2,...,MF. Thus the value which the kth
               derivative of each approximation (k=0 referring to the
               approximation itself) is required to take at the point XF(r)
               must be contained in YF(s), where
                                  s=r+k+p +p +...+p   ,
                                         1  2      r-1
               for k=0,1,...,p  and r = 1,2,...,MF. The derivatives are
                              r
               with respect to the user's variable x.

          12:  LYF -- INTEGER                                         Input
               On entry:
               the dimension of the array YF as declared in the
               (sub)program from which E02AGF is called.
               Constraint: LYF>=n, where n=MF+p +p +...+p  .
                                               1  2      MF

          13:  IP(MF) -- INTEGER array                                Input
               On entry: IP(r) must contain p , the order of the highest-
                                             r
               order derivative specified at XF(r), for r = 1,2,...,MF.
               p =0 implies that the value of the approximation at XF(r) is
                r
               specified, but not that of any derivative. Constraint: IP(r)
               >= 0, for r=1,2,...,MF.

          14:  A(NROWS,KPLUS1) -- DOUBLE PRECISION array             Output
               On exit: A(i+1,j+1) contains the coefficient a   in the
                                                             ij
               approximating polynomial of degree i, for i=n,n+1,...,k;
               j=0,1,...,i.

          15:  S(KPLUS1) -- DOUBLE PRECISION array                   Output
               On exit: S(i+1) contains s , for i=n,n+1,...,k, the root-
                                          i
               mean-square residual corresponding to the approximating
               polynomial of degree i. In the case where the number of data
               points with non-zero weight is equal to k+1-n, s  is
                                                               i
               indeterminate: the routine sets it to zero. For the
               interpretation of the values of s  and their use in
                                                i
               selecting an appropriate degree, see Section 3.1 of the
               Chapter Introduction.

          16:  NP1 -- INTEGER                                        Output
               On exit: n+1, where n is the total number of constraint
               conditions imposed: n=MF+p +p +...+p  .
                                         1  2      MF

          17:  WRK(LWRK) -- DOUBLE PRECISION array                   Output
               On exit: WRK contains weighted residuals of the highest
               degree of fit determined (k). The residual at x  is in
               element 2(n+1)+3(m+k+1)+r, for r=1,2,...,m. The rest of the
               array is used as workspace.

          18:  LWRK -- INTEGER                                        Input
               On entry:
               the dimension of the array WRK as declared in the
               (sub)program from which E02AGF is called.
               Constraint: LWRK>=max(4*M+3*KPLUS1, 8*n+5*IPMAX+MF+10)+2*n+2
               , where IPMAX = max(IP(R)).

          19:  IWRK(LIWRK) -- INTEGER array                       Workspace

          20:  LIWRK -- INTEGER                                       Input
               On entry:
               the dimension of the array IWRK as declared in the
               (sub)program from which E02AGF is called.
               Constraint: LIWRK>=2*MF+2.

          21:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               On entry M < 1,

               or       KPLUS1 < n + 1,

               or       NROWS < KPLUS1,

               or       MF < 1,

               or       LYF < n,

               or       LWRK is too small (see Section 5),

               or       LIWRK<2*MF+2.
               (Here n is the total number of constraint conditions.)

          IFAIL= 2
               IP(r) < 0 for some r = 1,2,...,MF.

          IFAIL= 3
               XMIN >= XMAX, or XF(r) is not in the interval XMIN to XMAX
               for some r = 1,2,...,MF, or the XF(r) are not distinct.

          IFAIL= 4
               X(r) is not in the interval XMIN to XMAX for some
               r=1,2,...,M.

          IFAIL= 5
               X(r) < X(r-1) for some r=2,3,...,M.

          IFAIL= 6
               KPLUS1>m''+n, where m'' is the number of data points with
               non-zero weight and distinct abscissae which do not coincide
               with any XF(r). Thus there is no unique solution.

          IFAIL= 7
               The polynomials (mu)(x) and/or (nu)(x) cannot be determined.
               The problem supplied is too ill-conditioned. This may occur
               when the constraint points are very close together, or large
               in number, or when an attempt is made to constrain high-
               order derivatives.

          7. Accuracy

          No complete error analysis exists for either the interpolating
          algorithm or the approximating algorithm. However, considerable
          experience with the approximating algorithm shows that it is
          generally extremely satisfactory. Also the moderate number of
          constraints, of low order, which are typical of data fitting
          applications, are unlikely to cause difficulty with the
          interpolating routine.

          8. Further Comments

          The time taken by the routine to form the interpolating
                                                       3
          polynomial is approximately proportional to n , and that to form
          the approximating polynomials is very approximately proportional
          to m(k+1)(k+1-n).

          To carry out a least-squares polynomial fit without constraints,
          use E02ADF. To carry out polynomial interpolation only, use
          E01AEF(*).

          9. Example

          The example program reads data in the following order, using the
          notation of the parameter list above:

               MF

               IP(i), XF(i), Y-value and derivative values (if any) at
               XF(i), for i= 1,2,...,MF

               M

               X(i), Y(i), W(i), for i=1,2,...,M

               k, XMIN, XMAX

          The output is:

               the root-mean-square residual for each degree from n to k;

               the Chebyshev coefficients for the fit of degree k;

               the data points, and the fitted values and residuals for
               the fit of degree k.

          The program is written in a generalized form which will read any
          number of data sets.

          The data set supplied specifies 5 data points in the interval [0.
          0,4.0] with unit weights, to which are to be fitted polynomials,
          p, of degrees up to 4, subject to the 3 constraints:

               p(0.0)=1.0,  p'(0.0)=-2.0,  p(4.0)=9.0.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02AHF
                  E02AHF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02AHF determines the coefficients in the Chebyshev-series
          representation of the derivative of a polynomial given in
          Chebyshev-series form.

          2. Specification

                 SUBROUTINE E02AHF (NP1, XMIN, XMAX, A, IA1, LA, PATM1,
                1                   ADIF, IADIF1, LADIF, IFAIL)
                 INTEGER          NP1, IA1, LA, IADIF1, LADIF, IFAIL
                 DOUBLE PRECISION XMIN, XMAX, A(LA), PATM1, ADIF(LADIF)

          3. Description

          This routine forms the polynomial which is the derivative of a
          given polynomial. Both the original polynomial and its derivative
          are represented in Chebyshev-series form. Given the coefficients
          a , for i=0,1,...,n, of a polynomial p(x) of degree n, where
           i

                                  1                    
                            p(x)= -a +a T (x)+...+a T (x)
                                  2 0  1 1         n n

                                               

          the routine returns the coefficients a , for i=0,1,...,n-1, of
                                                i
          the polynomial q(x) of degree n-1, where

                            dp(x)  1                        
                      q(x)= -----= -a +a T (x)+...+a   T   (x).
                             dx    2 0  1 1         n-1 n-1

                  

          Here T (x) denotes the Chebyshev polynomial of the first kind of
                j
                                 

          degree j with argument x. It is assumed that the normalised
                   

          variable x in the interval [-1,+1] was obtained from the user's
          original variable x in the interval [x   ,x   ] by the linear
                                                min  max
          transformation

                                     2x-(x   +x   )
                                          max  min
                                  x= --------------
                                       x   -x
                                        max  min

          and that the user requires the derivative to be with respect to
                                                            

          the variable x. If the derivative with respect to x is required,
          set x   =1 and x   =-1.
               max        min

          Values of the derivative can subsequently be computed, from the
          coefficients obtained, by using E02AKF.

          The method employed is that of [1] modified to obtain the
                                                               

          derivative with respect to x. Initially setting a   =a =0, the
                                                           n+1  n
          routine forms successively

                                    2
                     a   =a   + ---------2ia ,   i=n,n-1,...,1.
                      i-1  i+1  x   -x      i
                                 max  min

          4. References

          [1]   Unknown (1961) Chebyshev-series. Modern Computing Methods,
                Chapter 8. NPL Notes on Applied Science (2nd Edition). 16
                HMSO.

          5. Parameters

           1:  NP1 -- INTEGER                                         Input
               On entry: n+1, where n is the degree of the given
               polynomial p(x). Thus NP1 is the number of coefficients in
               this polynomial. Constraint: NP1 >= 1.

           2:  XMIN -- DOUBLE PRECISION                               Input

           3:  XMAX -- DOUBLE PRECISION                               Input
               On entry: the lower and upper end-points respectively of
               the interval [x   ,x   ]. The Chebyshev-series
                              min  max
                                                                     

               representation is in terms of the normalised variable x,
               where
                                       2x-(x   +x   )
                                            max  min
                                    x= --------------.
                                         x   -x
                                          max  min
               Constraint: XMAX > XMIN.

           4:  A(LA) -- DOUBLE PRECISION array                        Input
               On entry: the Chebyshev coefficients of the polynomial p(x).
               Specifically, element 1 + i*IA1 of A must contain the
               coefficient a , for i=0,1,...,n. Only these n+1 elements
                            i
               will be accessed.

               Unchanged on exit, but see ADIF, below.

           5:  IA1 -- INTEGER                                         Input
               On entry: the index increment of A. Most frequently the
               Chebyshev coefficients are stored in adjacent elements of A,
               and IA1 must be set to 1. However, if, for example, they are
               stored in A(1),A(4),A(7),..., then the value of IA1 must be
               3. See also Section 8. Constraint: IA1 >= 1.

           6:  LA -- INTEGER                                          Input
               On entry:
               the dimension of the array A as declared in the (sub)program
               from which E02AHF is called.
               Constraint: LA>=1+(NP1-1)*IA1.

           7:  PATM1 -- DOUBLE PRECISION                             Output
               On exit: the value of p(x   ). If this value is passed to
                                         min
               the integration routine E02AJF with the coefficients of q(x)
               , then the original polynomial p(x) is recovered, including
               its constant coefficient.

           8:  ADIF(LADIF) -- DOUBLE PRECISION array                 Output
               On exit: the Chebyshev coefficients of the derived
               polynomial q(x). (The differentiation is with respect to the
               variable x). Specifically, element 1+i*IADIF1 of ADIF
                                        

               contains the coefficient a , i=0,1,...n-1. Additionally
                                         i
               element 1+n*IADIF1 is set to zero. A call of the routine may
               have the array name ADIF the same as A, provided that note
               is taken of the order in which elements are overwritten,
               when choosing the starting elements and increments IA1 and
               IADIF1: i.e., the coefficients a ,a ,...,a    must be intact
                                               0  1      i-1
                                 

               after coefficient a  is stored. In particular, it is
                                  i
               possible to overwrite the a  completely by having IA1 =
                                          i
               IADIF1, and the actual arrays for A and ADIF identical.

           9:  IADIF1 -- INTEGER                                      Input
               On entry: the index increment of ADIF. Most frequently the
               Chebyshev coefficients are required in adjacent elements of
               ADIF, and IADIF1 must be set to 1. However, if, for example,
               they are to be stored in ADIF(1),ADIF(4),ADIF(7),..., then
               the value of IADIF1 must be 3. See Section 8. Constraint:
               IADIF1 >= 1.

          10:  LADIF -- INTEGER                                       Input
               On entry:
               the dimension of the array ADIF as declared in the
               (sub)program from which E02AHF is called.
               Constraint: LADIF>=1+(NP1-1)*IADIF1.

          11:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               On entry NP1 < 1,

               or       XMAX <= XMIN,

               or       IA1 < 1,

               or       LA<=(NP1-1)*IA1,

               or       IADIF1 < 1,

               or       LADIF<=(NP1-1)*IADIF1.

          7. Accuracy

          There is always a loss of precision in numerical differentiation,
          in this case associated with the multiplication by 2i in the
          formula quoted in Section 3.

          8. Further Comments

          The time taken by the routine is approximately proportional to
          n+1.

          The increments IA1, IADIF1 are included as parameters to give a
          degree of flexibility which, for example, allows a polynomial in
          two variables to be differentiated with respect to either
          variable without rearranging the coefficients.

          9. Example

          Suppose a polynomial has been computed in Chebyshev-series form
          to fit data over the interval [-0.5,2.5]. The example program
          evaluates the 1st and 2nd derivatives of this polynomial at 4
          equally spaced points over the interval. (For the purposes of
          this example, XMIN, XMAX and the Chebyshev coefficients are
          simply supplied in DATA statements. Normally a program would
          first read in or generate data and compute the fitted
          polynomial.)

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02AJF
                  E02AJF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02AJF determines the coefficients in the Chebyshev-series
          representation of the indefinite integral of a polynomial given
          in Chebyshev-series form.

          2. Specification

                 SUBROUTINE E02AJF (NP1, XMIN, XMAX, A, IA1, LA, QATM1,
                1                   AINT, IAINT1, LAINT, IFAIL)
                 INTEGER          NP1, IA1, LA, IAINT1, LAINT, IFAIL
                 DOUBLE PRECISION XMIN, XMAX, A(LA), QATM1, AINT(LAINT)

          3. Description

          This routine forms the polynomial which is the indefinite
          integral of a given polynomial. Both the original polynomial and
          its integral are represented in Chebyshev-series form. If
          supplied with the coefficients a , for i=0,1,...,n, of a
                                          i
          polynomial p(x) of degree n, where

                                 1                    
                           p(x)= -a +a T (x)+...+a T (x),
                                 2 0  1 1         n n

          the routine returns the coefficients a' , for i=0,1,...,n+1, of
                                                 i
          the polynomial q(x) of degree n+1, where

                              1                           
                        q(x)= -a' +a' T (x)+...+a'   T   (x),
                              2  0   1 1          n+1 n+1

          and

                                         /
                                   q(x)= |p(x)dx.
                                         /

                  

          Here T (x) denotes the Chebyshev polynomial of the first kind of
                j
          degree j with argument x. It is assumed that the normalised
                   

          variable x in the interval [-1,+1] was obtained from the user's
          original variable x in the interval [x   ,x   ] by the linear
                                                min  max
          transformation

                                     2x-(x   +x   )
                                          max  min
                                  x= --------------
                                       x   -x
                                        max  min

          and that the user requires the integral to be with respect to the
                                                      

          variable x. If the integral with respect to x is required, set
          x   =1 and x   =-1.
           max        min

          Values of the integral can subsequently be computed, from the
          coefficients obtained, by using E02AKF.

          The method employed is that of Chebyshev-series [1] modified for
          integrating with respect to x. Initially taking a   =a   =0, the
                                                           n+1  n+2
          routine forms successively

                          a   -a     x   -x
                           i-1  i+1   max  min
                     a' = ---------* ---------,   i=n+1,n,...,1.
                       i     2i          2

          The constant coefficient a'  is chosen so that q(x) is equal to a
                                     0
          specified value, QATM1, at the lower end-point of the interval on
                                     

          which it is defined, i.e., x=-1, which corresponds to x=x   .
                                                                   min

          4. References

          [1]   Unknown (1961) Chebyshev-series. Modern Computing Methods,
                Chapter 8. NPL Notes on Applied Science (2nd Edition). 16
                HMSO.

          5. Parameters

           1:  NP1 -- INTEGER                                         Input
               On entry: n+1, where n is the degree of the given
               polynomial p(x). Thus NP1 is the number of coefficients in
               this polynomial. Constraint: NP1 >= 1.

           2:  XMIN -- DOUBLE PRECISION                               Input

           3:  XMAX -- DOUBLE PRECISION                               Input
               On entry: the lower and upper end-points respectively of
               the interval [x   ,x   ]. The Chebyshev-series
                              min  max
                                                                     

               representation is in terms of the normalised variable x,
               where
                                       2x-(x   +x   )
                                            max  min
                                    x= --------------.
                                         x   -x
                                          max  min
               Constraint: XMAX > XMIN.

           4:  A(LA) -- DOUBLE PRECISION array                        Input
               On entry: the Chebyshev coefficients of the polynomial p(x)
               . Specifically, element 1+i*IA1 of A must contain the
               coefficient a , for i=0,1,...,n. Only these n+1 elements
                            i
               will be accessed.

               Unchanged on exit, but see AINT, below.

           5:  IA1 -- INTEGER                                         Input
               On entry: the index increment of A. Most frequently the
               Chebyshev coefficients are stored in adjacent elements of A,
               and IA1 must be set to 1. However, if for example, they are
               stored in A(1),A(4),A(7),..., then the value of IA1 must be
               3. See also Section 8. Constraint: IA1 >= 1.

           6:  LA -- INTEGER                                          Input
               On entry:
               the dimension of the array A as declared in the (sub)program
               from which E02AJF is called.
               Constraint: LA>=1+(NP1-1)*IA1.

           7:  QATM1 -- DOUBLE PRECISION                              Input
               On entry: the value that the integrated polynomial is
               required to have at the lower end-point of its interval of
                                    

               definition, i.e., at x=-1 which corresponds to x=x   . Thus,
                                                                 min
               QATM1 is a constant of integration and will normally be set
               to zero by the user.

           8:  AINT(LAINT) -- DOUBLE PRECISION array                 Output
               On exit: the Chebyshev coefficients of the integral q(x).
               (The integration is with respect to the variable x, and the
               constant coefficient is chosen so that q(x   ) equals QATM1)
                                                         min
               Specifically, element 1+i*IAINT1 of AINT contains the
               coefficient a' , for i=0,1,...,n+1. A call of the routine
                             i
               may have the array name AINT the same as A, provided that
               note is taken of the order in which elements are overwritten
               when choosing starting elements and increments IA1 and
               IAINT1: i.e., the coefficients, a ,a ,...,a    must be
                                                0  1      i-2
               intact after coefficient a'  is stored. In particular it is
                                          i
               possible to overwrite the a  entirely by having IA1 =
                                          i
               IAINT1, and the actual array for A and AINT identical.

           9:  IAINT1 -- INTEGER                                      Input
               On entry: the index increment of AINT. Most frequently the
               Chebyshev coefficients are required in adjacent elements of
               AINT, and IAINT1 must be set to 1. However, if, for example,
               they are to be stored in AINT(1),AINT(4),AINT(7),..., then
               the value of IAINT1 must be 3. See also Section 8.
               Constraint: IAINT1 >= 1.

          10:  LAINT -- INTEGER                                       Input
               On entry:
               the dimension of the array AINT as declared in the
               (sub)program from which E02AJF is called.
               Constraint: LAINT>=1+NP1*IAINT1.

          11:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               On entry NP1 < 1,

               or       XMAX <= XMIN,

               or       IA1 < 1,

               or       LA<=(NP1-1)*IA1,

               or       IAINT1 < 1,

               or       LAINT<=NP1*IAINT1.

          7. Accuracy

          In general there is a gain in precision in numerical integration,
          in this case associated with the division by 2i in the formula
          quoted in Section 3.

          8. Further Comments

          The time taken by the routine is approximately proportional to
          n+1.

          The increments IA1, IAINT1 are included as parameters to give a
          degree of flexibility which, for example, allows a polynomial in
          two variables to be integrated with respect to either variable
          without rearranging the coefficients.

          9. Example

          Suppose a polynomial has been computed in Chebyshev-series form
          to fit data over the interval [-0.5,2.5]. The example program
          evaluates the integral of the polynomial from 0.0 to 2.0. (For
          the purpose of this example, XMIN, XMAX and the Chebyshev
          coefficients are simply supplied in DATA statements. Normally a
          program would read in or generate data and compute the fitted
          polynomial).

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02AKF
                  E02AKF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02AKF evaluates a polynomial from its Chebyshev-series
          representation, allowing an arbitrary index increment for
          accessing the array of coefficients.

          2. Specification

                 SUBROUTINE E02AKF (NP1, XMIN, XMAX, A, IA1, LA, X, RESULT,
                1                   IFAIL)
                 INTEGER          NP1, IA1, LA, IFAIL
                 DOUBLE PRECISION XMIN, XMAX, A(LA), X, RESULT

          3. Description

          If supplied with the coefficients a , for i=0,1,...,n, of a
                                             i
                       

          polynomial p(x) of degree n, where

                                 1                    
                           p(x)= -a +a T (x)+...+a T (x),
                                 2 0  1 1         n n

                                              

          this routine returns the value of p(x) at a user-specified value
                                     

          of the variable x. Here T (x) denotes the Chebyshev polynomial of
                                   j
                                                   

          the first kind of degree j with argument x. It is assumed that
                                   

          the independent variable x in the interval [-1,+1] was obtained
          from the user's original variable x in the interval [x   ,x   ]
                                                                min  max
          by the linear transformation

                                    2x-(x   +x   )
                                         max  min
                                 x= --------------.
                                      x   -x
                                       max  min

          The coefficients a  may be supplied in the array A, with any
                            i
          increment between the indices of array elements which contain
          successive coefficients. This enables the routine to be used in
          surface fitting and other applications, in which the array might
          have two or more dimensions.

          The method employed is based upon the three-term recurrence
          relation due to Clenshaw [1], with modifications due to Reinsch
          and Gentleman (see [4]). For further details of the algorithm and
          its use see Cox [2] and Cox and Hayes [3].

          4. References

          [1]   Clenshaw C W (1955) A Note on the Summation of Chebyshev-
                series. Math. Tables Aids Comput. 9 118--120.

          [2]   Cox M G (1973) A data-fitting package for the non-specialist
                user. Report NAC40. National Physical Laboratory.

          [3]   Cox M G and Hayes J G (1973) Curve fitting: a guide and
                suite of algorithms for the non-specialist user. Report
                NAC26. National Physical Laboratory.

          [4]   Gentlemen W M (1969) An Error Analysis of Goertzel's
                (Watt's) Method for Computing Fourier Coefficients. Comput.
                J. 12 160--165.

          5. Parameters

           1:  NP1 -- INTEGER                                         Input
               On entry: n+1, where n is the degree of the given
                            

               polynomial p(x). Constraint: NP1 >= 1.

           2:  XMIN -- DOUBLE PRECISION                               Input

           3:  XMAX -- DOUBLE PRECISION                               Input
               On entry: the lower and upper end-points respectively of
               the interval [x   ,x   ]. The Chebyshev-series
                              min  max
                                                                     

               representation is in terms of the normalised variable x,
               where
                                       2x-(x   +x   )
                                            max  min
                                    x= --------------.
                                         x   -x
                                          max  min
               Constraint: XMIN < XMAX.

           4:  A(LA) -- DOUBLE PRECISION array                        Input
               On entry: the Chebyshev coefficients of the polynomial p(x).
               Specifically, element 1+i*IA1 must contain the coefficient
               a , for i=0,1,...,n. Only these n+1 elements will be
                i
               accessed.

           5:  IA1 -- INTEGER                                         Input
               On entry: the index increment of A. Most frequently, the
               Chebyshev coefficients are stored in adjacent elements of A,
               and IA1 must be set to 1. However, if, for example, they are
               stored in A(1),A(4),A(7),..., then the value of IA1 must be
               3. Constraint: IA1 >= 1.

           6:  LA -- INTEGER                                          Input
               On entry:
               the dimension of the array A as declared in the (sub)program
               from which E02AKF is called.
               Constraint: LA>=(NP1-1)*IA1+1.

           7:  X -- DOUBLE PRECISION                                  Input
               On entry: the argument x at which the polynomial is to be
               evaluated. Constraint: XMIN <= X <= XMAX.

           8:  RESULT -- DOUBLE PRECISION                            Output
                                                      

               On exit: the value of the polynomial p(x).

           9:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               On entry NP1 < 1,

               or       IA1 < 1,

               or       LA<=(NP1-1)*IA1,

               or       XMIN >= XMAX.

          IFAIL= 2
               X does not satisfy the restriction XMIN <= X <= XMAX.

          7. Accuracy

          The rounding errors are such that the computed value of the
          polynomial is exact for a slightly perturbed set of coefficients
          a +(delta)a . The ratio of the sum of the absolute values of the
           i         i
          (delta)a  to the sum of the absolute values of the a  is less
                  i                                           i
          than a small multiple of (n+1)*machine precision.

          8. Further Comments

          The time taken by the routine is approximately proportional to
          n+1.

          9. Example

          Suppose a polynomial has been computed in Chebyshev-series form
          to fit data over the interval [-0.5,2.5]. The example program
          evaluates the polynomial at 4 equally spaced points over the
          interval. (For the purposes of this example, XMIN, XMAX and the
          Chebyshev coefficients are supplied in DATA statements. Normally
          a program would first read in or generate data and compute the
          fitted polynomial.)

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02BAF
                  E02BAF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02BAF computes a weighted least-squares approximation to an
          arbitrary set of data points by a cubic spline with knots
          prescribed by the user. Cubic spline interpolation can also be
          carried out.

          2. Specification

                 SUBROUTINE E02BAF (M, NCAP7, X, Y, W, LAMDA, WORK1, WORK2,
                1                   C, SS, IFAIL)
                 INTEGER          M, NCAP7, IFAIL
                 DOUBLE PRECISION X(M), Y(M), W(M), LAMDA(NCAP7), WORK1(M),
                1                 WORK2(4*NCAP7), C(NCAP7), SS

          3. Description

          This routine determines a least-squares cubic spline
          approximation s(x) to the set of data points (x ,y ) with weights
                                                         r  r
                                                               

          w , for r=1,2,...,m. The value of NCAP7 = n+7, where n is the
           r
          number of intervals of the spline (one greater than the number of
          interior knots), and the values of the knots
          (lambda) ,(lambda) ,...,(lambda)   , interior to the data
                  5         6             n+3
          interval, are prescribed by the user.

          s(x) has the property that it minimizes (theta), the sum of
          squares of the weighted residuals (epsilon) , for r=1,2,...,m,
                                                     r
          where

                              (epsilon) =w (y -s(x )).
                                       r  r  r    r

          The routine produces this minimizing value of (theta) and the
                                             

          coefficients c ,c ,...,c , where q=n+3, in the B-spline
                        1  2      q
          representation

                                        q
                                        --
                                  s(x)= >  c N (x).
                                        --  i i
                                        i=1

          Here N (x) denotes the normalised B-spline of degree 3 defined
                i
          upon the knots (lambda) ,(lambda)   ,...,(lambda)   .
                                 i         i+1             i+4

          In order to define the full set of B-splines required, eight
          additional knots (lambda) ,(lambda) ,(lambda) ,(lambda)  and
                                   1         2         3         4
          (lambda)   ,(lambda)-  ,(lambda)   ,(lambda)    are inserted
                  n+4         n+5         n+6         n+7
          automatically by the routine. The first four of these are set
          equal to the smallest x  and the last four to the largest x .
                                 r                                   r

          The representation of s(x) in terms of B-splines is the most

          compact form possible in that only n+3 coefficients, in addition
                 

          to the n+7 knots, fully define s(x).

          The method employed involves forming and then computing the
          least-squares solution of a set of m linear equations in the
                                     

          coefficients c  (i=1,2,...,n+3). The equations are formed using a
                        i
          recurrence relation for B-splines that is unconditionally stable
          (Cox [1], de Boor [5]), even for multiple (coincident) knots. The
          least-squares solution is also obtained in a stable manner by
          using orthogonal transformations, viz. a variant of Givens
          rotations (Gentleman [6] and [7]). This requires only one
          equation to be stored at a time. Full advantage is taken of the
          structure of the equations, there being at most four non-zero
          values of N (x) for any value of x and hence at most four
                     i
          coefficients in each equation.

          For further details of the algorithm and its use see Cox [2], [3]
          and [4].

          Subsequent evaluation of s(x) from its B-spline representation
          may be carried out using E02BBF. If derivatives of s(x) are also
          required, E02BCF may be used. E02BDF can be used to compute the
          definite integral of s(x).

          4. References

          [1]   Cox M G (1972) The Numerical Evaluation of B-splines. J.
                Inst. Math. Appl. 10 134--149.

          [2]   Cox M G (1974) A Data-fitting Package for the Non-specialist
                User. Software for Numerical Mathematics. (ed D J Evans)
                Academic Press.

          [3]   Cox M G (1975) Numerical methods for the interpolation and
                approximation of data by spline functions. PhD Thesis. City
                University, London.

          [4]   Cox M G and Hayes J G (1973) Curve fitting: a guide and
                suite of algorithms for the non-specialist user. Report
                NAC26. National Physical Laboratory.

          [5]   De Boor C (1972) On Calculating with B-splines. J. Approx.
                Theory. 6 50--62.

          [6]   Gentleman W M (1974) Algorithm AS 75. Basic Procedures for
                Large Sparse or Weighted Linear Least-squares Problems.
                Appl. Statist. 23 448--454.

          [7]   Gentleman W M (1973) Least-squares Computations by Givens
                Transformations without Square Roots. J. Inst. Math. Applic.
                12 329--336.

          [8]   Schoenberg I J and Whitney A (1953) On Polya Frequency
                Functions III. Trans. Amer. Math. Soc. 74  246--259.

          5. Parameters

           1:  M -- INTEGER                                           Input
               On entry: the number m of data points. Constraint: M >=
               MDIST >= 4, where MDIST is the number of distinct x values
               in the data.

           2:  NCAP7 -- INTEGER                                       Input
                                    

               On entry: n+7, where n is the number of intervals of the
               spline (which is one greater than the number of interior
               knots, i.e., the knots strictly within the range x  to x )
                                                                 1     m
               over which the spline is defined. Constraint: 8 <= NCAP7 <=
               MDIST + 4, where MDIST is the number of distinct x values in
               the data.

           3:  X(M) -- DOUBLE PRECISION array                         Input
               On entry: the values x  of the independent variable
                                     r
               (abscissa), for r=1,2,...,m. Constraint: x <=x <=...<=x .
                                                         1   2        m

           4:  Y(M) -- DOUBLE PRECISION array                         Input
               On entry: the values y  of the dependent variable
                                     r
               (ordinate), for r=1,2,...,m.

           5:  W(M) -- DOUBLE PRECISION array                         Input
               On entry: the values w  of the weights, for r=1,2,...,m.
                                     r
               For advice on the choice of weights, see the Chapter
               Introduction. Constraint: W(r) > 0, for r=1,2,...,m.

           6:  LAMDA(NCAP7) -- DOUBLE PRECISION array          Input/Output
               On entry: LAMDA(i) must be set to the (i-4)th (interior)

               knot, (lambda) , for i=5,6,...,n+3. Constraint: X(1) < LAMDA
                             i
               (5) <= LAMDA(6) <=... <= LAMDA(NCAP7-4) < X(M). On exit: the
               input values are unchanged, and LAMDA(i), for i = 1, 2, 3,
               4, NCAP7-3, NCAP7-2, NCAP7-1, NCAP7 contains the additional
               (exterior) knots introduced by the routine. For advice on
               the choice of knots, see Section 3.3 of the Chapter
               Introduction.

           7:  WORK1(M) -- DOUBLE PRECISION array                 Workspace

           8:  WORK2(4*NCAP7) -- DOUBLE PRECISION array           Workspace

           9:  C(NCAP7) -- DOUBLE PRECISION array                    Output
               On exit: the coefficient c  of the B-spline N (x), for
                                         i                  i
                         

               i=1,2,...,n+3. The remaining elements of the array are not
               used.

          10:  SS -- DOUBLE PRECISION                                Output
               On exit: the residual sum of squares, (theta).

          11:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               The knots fail to satisfy the condition

               X(1) < LAMDA(5) <= LAMDA(6) <=... <= LAMDA(NCAP7-4) < X(M).
               Thus the knots are not in correct order or are not interior
               to the data interval.

          IFAIL= 2
               The weights are not all strictly positive.

          IFAIL= 3
               The values of X(r), for r = 1,2,...,M are not in non-
               decreasing order.

          IFAIL= 4
               NCAP7 < 8 (so the number of interior knots is negative) or
               NCAP7 > MDIST + 4, where MDIST is the number of distinct x
               values in the data (so there cannot be a unique solution).

          IFAIL= 5
               The conditions specified by Schoenberg and Whitney [8] fail
               to hold for at least one subset of the distinct data
               abscissae. That is, there is no subset of NCAP7-4 strictly
               increasing values, X(R(1)),X(R(2)),...,X(R(NCAP7-4)), among
               the abscissae such that
                    X(R(1)) < LAMDA(1) < X(R(5)),

                    X(R(2)) < LAMDA(2) < X(R(6)),

                    ...

                    X(R(NCAP7-8)) < LAMDA(NCAP7-8) < X(R(NCAP7-4)).
               This means that there is no unique solution: there are
               regions containing too many knots compared with the number
               of data points.

          7. Accuracy

          The rounding errors committed are such that the computed
          coefficients are exact for a slightly perturbed set of ordinates
          y +(delta)y . The ratio of the root-mean-square value for the
           r         r
          (delta)y  to the root-mean-square value of the y  can be expected
                  r                                       r
          to be less than a small multiple of (kappa)*m*machine precision,
          where (kappa) is a condition number for the problem. Values of
          (kappa) for 20-30 practical data sets all proved to lie between
          4.5 and 7.8 (see Cox [3]). (Note that for these data sets,
          replacing the coincident end knots at the end-points x  and x
                                                                1      m
          used in the routine by various choices of non-coincident exterior
          knots gave values of (kappa) between 16 and 180. Again see Cox
          [3] for further details.) In general we would not expect (kappa)
          to be large unless the choice of knots results in near-violation
          of the Schoenberg-Whitney conditions.

          A cubic spline which adequately fits the data and is free from
          spurious oscillations is more likely to be obtained if the knots
          are chosen to be grouped more closely in regions where the
          function (underlying the data) or its derivatives change more
          rapidly than elsewhere.

          8. Further Comments

                                                               

          The time taken by the routine is approximately C*(2m+n+7)
          seconds, where C is a machine-dependent constant.

          Multiple knots are permitted as long as their multiplicity does
          not exceed 4, i.e., the complete set of knots must satisfy
                                               

          (lambda) <(lambda)   , for i=1,2,...,n+3, (cf. Section 6). At a
                  i         i+4
          knot of multiplicity one (the usual case), s(x) and its first two
          derivatives are continuous. At a knot of multiplicity two, s(x)
          and its first derivative are continuous. At a knot of
          multiplicity three, s(x) is continuous, and at a knot of
          multiplicity four, s(x) is generally discontinous.

          The routine can be used efficiently for cubic spline
                                   

          interpolation, i.e.,if m=n+3. The abscissae must then of course
          satisfy x <x <...<x . Recommended values for the knots in this
                   1  2      m
                                                 

          case are (lambda) =x   , for i=5,6,...,n+3.
                           i  i-2

          9. Example

          Determine a weighted least-squares cubic spline approximation
          with five intervals (four interior knots) to a set of 14 given
          data points. Tabulate the data and the corresponding values of
          the approximating spline, together with the residual errors, and
          also the values of the approximating spline at points half-way
          between each pair of adjacent data points.

          The example program is written in a general form that will enable
                                                         

          a cubic spline approximation with n intervals (n-1 interior
          knots) to be obtained to m data points, with arbitrary positive
          weights, and the approximation to be tabulated. Note that E02BBF
          is used to evaluate the approximating spline. The program is
          self-starting in that any number of data sets can be supplied.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02BBF
                  E02BBF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02BBF evaluates a cubic spline from its B-spline representation.

          2. Specification

                 SUBROUTINE E02BBF (NCAP7, LAMDA, C, X, S, IFAIL)
                 INTEGER          NCAP7, IFAIL
                 DOUBLE PRECISION LAMDA(NCAP7), C(NCAP7), X, S

          3. Description

          This routine evaluates the cubic spline s(x) at a prescribed
          argument x from its augmented knot set (lambda) , for
                                                         i
                    

          i=1,2,...,n+7, (see E02BAF) and from the coefficients c , for
                                                                 i
          i=1,2,...,q in its B-spline representation

                                        q
                                        --
                                  s(x)= >  c N (x)
                                        --  i i
                                        i=1

                            

          Here q=n+3, where n is the number of intervals of the spline, and
          N (x) denotes the normalised B-spline of degree 3 defined upon
           i
          the knots (lambda) ,(lambda)   ,...,(lambda)   . The prescribed
                            i         i+1             i+4
          argument x must satisfy (lambda) <=x<=(lambda)   .
                                          4             n+4

                                                                   

          It is assumed that (lambda) >=(lambda)   , for j=2,3,...,n+7, and
                                     j          j-1
          (lambda)   >(lambda) .
                              4
                  n+4

          The method employed is that of evaluation by taking convex
          combinations due to de Boor [4]. For further details of the
          algorithm and its use see Cox [1] and [3].

          It is expected that a common use of E02BBF will be the evaluation
          of the cubic spline approximations produced by E02BAF. A
          generalization of E02BBF which also forms the derivative of s(x)
          is E02BCF. E02BCF takes about 50% longer than E02BBF.

          4. References

          [1]   Cox M G (1972) The Numerical Evaluation of B-splines. J.
                Inst. Math. Appl. 10 134--149.

          [2]   Cox M G (1978) The Numerical Evaluation of a Spline from its
                B-spline Representation. J. Inst. Math. Appl. 21 135--143.

          [3]   Cox M G and Hayes J G (1973) Curve fitting: a guide and
                suite of algorithms for the non-specialist user. Report
                NAC26. National Physical Laboratory.

          [4]   De Boor C (1972) On Calculating with B-splines. J. Approx.
                Theory. 6 50--62.

          5. Parameters

           1:  NCAP7 -- INTEGER                                       Input
                                    

               On entry: n+7, where n is the number of intervals (one
               greater than the number of interior knots, i.e., the knots
               strictly within the range (lambda)  to (lambda)   ) over
                                                 4            
                                                              n+4
               which the spline is defined. Constraint: NCAP7 >= 8.

           2:  LAMDA(NCAP7) -- DOUBLE PRECISION array                 Input
               On entry: LAMDA(j) must be set to the value of the jth
               member of the complete set of knots, (lambda)  for
                                                            j
                         

               j=1,2,...,n+7. Constraint: the LAMDA(j) must be in non-
               decreasing order with LAMDA(NCAP7-3) > LAMDA(4).

           3:  C(NCAP7) -- DOUBLE PRECISION array                     Input
               On entry: the coefficient c  of the B-spline N (x), for
                                          i                  i
                         

               i=1,2,...,n+3. The remaining elements of the array are not
               used.

           4:  X -- DOUBLE PRECISION                                  Input
               On entry: the argument x at which the cubic spline is to be
               evaluated. Constraint: LAMDA(4) <= X <= LAMDA(NCAP7-3).

           5:  S -- DOUBLE PRECISION                                 Output
               On exit: the value of the spline, s(x).

           6:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               The argument X does not satisfy LAMDA(4) <= X <= LAMDA(
               NCAP7-3).

               In this case the value of S is set arbitrarily to zero.

          IFAIL= 2
               NCAP7 < 8, i.e., the number of interior knots is negative.

          7. Accuracy

          The computed value of s(x) has negligible error in most practical
          situations. Specifically, this value has an absolute error
          bounded in modulus by 18*c   * machine precision, where c    is
                                    max                            max
          the largest in modulus of c ,c   ,c    and c   , and j is an
                                     j  j+1  j+2      j+3
          integer such that (lambda)   <=x<=(lambda)   . If c ,c   ,c
                                    j+3             j+4      j  j+1  j+2
          and c    are all of the same sign, then the computed value of
               j+3
          s(x) has a relative error not exceeding 20*machine precision in
          modulus. For further details see Cox [2].

          8. Further Comments

                                                                      

          The time taken by the routine is approximately C*(1+0.1*log(n+7))
          seconds, where C is a machine-dependent constant.

          Note: the routine does not test all the conditions on the knots
          given in the description of LAMDA in Section 5, since to do this
          would result in a computation time approximately linear in n+7
          instead of log(n+7). All the conditions are tested in E02BAF,
          however.

          9. Example

          Evaluate at 9 equally-spaced points in the interval 1.0<=x<=9.0
          the cubic spline with (augmented) knots 1.0, 1.0, 1.0, 1.0, 3.0,
          6.0, 8.0, 9.0, 9.0, 9.0, 9.0 and normalised cubic B-spline
          coefficients 1.0, 2.0, 4.0, 7.0, 6.0, 4.0, 3.0.

          The example program is written in a general form that will enable
                              

          a cubic spline with n intervals, in its normalised cubic B-spline
          form, to be evaluated at m equally-spaced points in the interval
                                 

          LAMDA(4) <= x <= LAMDA(n+4). The program is self-starting in that
          any number of data sets may be supplied.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02BCF
                  E02BCF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02BCF evaluates a cubic spline and its first three derivatives
          from its B-spline representation.

          2. Specification

                 SUBROUTINE E02BCF (NCAP7, LAMDA, C, X, LEFT, S, IFAIL)
                 INTEGER          NCAP7, LEFT, IFAIL
                 DOUBLE PRECISION LAMDA(NCAP7), C(NCAP7), X, S(4)

          3. Description

          This routine evaluates the cubic spline s(x) and its first three
          derivatives at a prescribed argument x. It is assumed that s(x)
          is represented in terms of its B-spline coefficients c , for
                                                                i
                    

          i=1,2,...,n+3 and (augmented) ordered knot set (lambda) , for
                                                                 i
                    

          i=1,2,...,n+7, (see E02BAF), i.e.,

                                        q
                                        --
                                  s(x)= >  c N (x)
                                        --  i i
                                        i=1

                      

          Here q=n+3, n is the number of intervals of the spline and N (x)
                                                                      i
          denotes the normalised B-spline of degree 3 (order 4) defined
          upon the knots (lambda) ,(lambda)   ,...,(lambda)   . The
                                 i         i+1             i+4
          prescribed argument x must satisfy

                              (lambda) <=x<=(lambda)
                                      4             n+4

          At a simple knot (lambda)  (i.e., one satisfying
                                   i
          (lambda)   <(lambda) <(lambda)   ), the third derivative of the
                  i-1         i         i+1
          spline is in general discontinuous. At a multiple knot (i.e., two
          or more knots with the same value), lower derivatives, and even
          the spline itself, may be discontinuous. Specifically, at a point
          x=u where (exactly) r knots coincide (such a point is termed a
          knot of multiplicity r), the values of the derivatives of order
          4-j, for j=1,2,...,r, are in general discontinuous. (Here
          1<=r<=4;r>4 is not meaningful.) The user must specify whether the
          value at such a point is required to be the left- or right-hand
          derivative.

          The method employed is based upon:

               (i) carrying out a binary search for the knot interval
               containing the argument x (see Cox [3]),

               (ii) evaluating the non-zero B-splines of orders 1,2,3 and
               4 by recurrence (see Cox [2] and [3]),

               (iii) computing all derivatives of the B-splines of order 4
               by applying a second recurrence to these computed B-spline
               values (see de Boor [1]),

               (iv) multiplying the 4th-order B-spline values and their
               derivative by the appropriate B-spline coefficients, and
               summing, to yield the values of s(x) and its derivatives.

          E02BCF can be used to compute the values and derivatives of cubic
          spline fits and interpolants produced by E02BAF.

          If only values and not derivatives are required, E02BBF may be
          used instead of E02BCF, which takes about 50% longer than E02BBF.

          4. References

          [1]   De Boor C (1972) On Calculating with B-splines. J. Approx.
                Theory. 6 50--62.

          [2]   Cox M G (1972) The Numerical Evaluation of B-splines. J.
                Inst. Math. Appl. 10 134--149.

          [3]   Cox M G (1978) The Numerical Evaluation of a Spline from its
                B-spline Representation. J. Inst. Math. Appl. 21 135--143.

          5. Parameters

           1:  NCAP7 -- INTEGER                                       Input
                                    

               On entry: n+7, where n is the number of intervals of the
               spline (which is one greater than the number of interior
               knots, i.e., the knots strictly within the range (lambda)
                                                                        4
               to (lambda)    over which the spline is defined).
                          n+4
               Constraint: NCAP7 >= 8.

           2:  LAMDA(NCAP7) -- DOUBLE PRECISION array                 Input
               On entry: LAMDA(j) must be set to the value of the jth
               member of the complete set of knots, (lambda) , for
                                                            j
                         

               j=1,2,...,n+7. Constraint: the LAMDA(j) must be in non-
               decreasing order with

               LAMDA(NCAP7-3) > LAMDA(4).

           3:  C(NCAP7) -- DOUBLE PRECISION array                     Input
               On entry: the coefficient c  of the B-spline N (x), for
                                          i                  i

               i=1,2,...,n+3. The remaining elements of the array are not
               used.

           4:  X -- DOUBLE PRECISION                                  Input
               On entry: the argument x at which the cubic spline and its
               derivatives are to be evaluated. Constraint: LAMDA(4) <= X
               <= LAMDA(NCAP7-3).

           5:  LEFT -- INTEGER                                        Input
               On entry: specifies whether left- or right-hand values of
               the spline and its derivatives are to be computed (see
               Section 3). Left- or right-hand values are formed according
               to whether LEFT is equal or not equal to 1. If x does not
               coincide with a knot, the value of LEFT is immaterial. If x
               = LAMDA(4), right-hand values are computed, and if x = LAMDA
               (NCAP7-3), left-hand values are formed, regardless of the
               value of LEFT.

           6:  S(4) -- DOUBLE PRECISION array                        Output
               On exit: S(j) contains the value of the (j-1)th derivative
               of the spline at the argument x, for j = 1,2,3,4. Note that
               S(1) contains the value of the spline.

           7:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               NCAP7 < 8, i.e., the number of intervals is not positive.

          IFAIL= 2
               Either LAMDA(4) >= LAMDA(NCAP7-3), i.e., the range over
               which s(x) is defined is null or negative in length, or X is
               an invalid argument, i.e., X < LAMDA(4) or X >
               LAMDA(NCAP7-3).

          7. Accuracy

          The computed value of s(x) has negligible error in most practical
          situations. Specifically, this value has an absolute error
          bounded in modulus by 18*c   * machine precision, where c    is
                                    max                            max
          the largest in modulus of c ,c   ,c    and c   , and j is an
                                     j  j+1  j+2      j+3
          integer such that (lambda)   <=x<=(lambda)   . If c ,c   ,c
                                    j+3             j+4      j  j+1  j+2
          and c    are all of the same sign, then the computed value of
               j+3
          s(x) has relative error bounded by 18*machine precision. For full
          details see Cox [3].

          No complete error analysis is available for the computation of
          the derivatives of s(x). However, for most practical purposes the
          absolute errors in the computed derivatives should be small.

          8. Further Comments

          The time taken by this routine is approximately linear in
              

          log(n+7).

          Note: the routine does not test all the conditions on the knots
          given in the description of LAMDA in Section 5, since to do this
                                                                     

          would result in a computation time approximately linear in n+7
                         

          instead of log(n+7). All the conditions are tested in E02BAF,
          however.

          9. Example

          Compute, at the 7 arguments x = 0, 1, 2, 3, 4, 5, 6, the left-
          and right-hand values and first 3 derivatives of the cubic spline
          defined over the interval 0<=x<=6 having the 6 interior knots x =
          1, 3, 3, 3, 4, 4, the 8 additional knots 0, 0, 0, 0, 6, 6, 6, 6,
          and the 10 B-spline coefficients 10, 12, 13, 15, 22, 26, 24, 18,
          14, 12.

          The input data items (using the notation of Section 5) comprise
          the following values in the order indicated:

              

              n           m

              LAMDA(j),   for j= 1,2,...,NCAP7

              C(j),       for j= 1,2,...,NCAP7-4

              x(i),       for i=1,2,...,m

          The example program is written in a general form that will enable
          the values and derivatives of a cubic spline having an arbitrary
          number of knots to be evaluated at a set of arbitrary points. Any
          number of data sets may be supplied. The only changes required to
          the program relate to the dimensions of the arrays LAMDA and C.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02BDF
                  E02BDF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02BDF computes the definite integral of a cubic spline from its
          B-spline representation.

          2. Specification

                 SUBROUTINE E02BDF (NCAP7, LAMDA, C, DEFINT, IFAIL)
                 INTEGER          NCAP7, IFAIL
                 DOUBLE PRECISION LAMDA(NCAP7), C(NCAP7), DEFINT

          3. Description

          This routine computes the definite integral of the cubic spline
          s(x) between the limits x=a and x=b, where a and b are
          respectively the lower and upper limits of the range over which
          s(x) is defined. It is assumed that s(x) is represented in terms
                                                         

          of its B-spline coefficients c , for i=1,2,...,n+3 and
                                        i
                                                                

          (augmented) ordered knot set (lambda) , for i=1,2,...,n+7, with
                                               i
          (lambda) =a, for i = 1,2,3,4 and (lambda) =b, for
                  i                                i
                        

          i=n+4,n+5,n+6,n+7, (see E02BAF), i.e.,

                                        q
                                        --
                                  s(x)= >  c N (x).
                                        --  i i
                                        i=1

                      

          Here q=n+3, n is the number of intervals of the spline and N (x)
                                                                      i
          denotes the normalised B-spline of degree 3 (order 4) defined
          upon the knots (lambda) ,(lambda)   ,...,(lambda)   .
                                 i         i+1             i+4

          The method employed uses the formula given in Section 3 of Cox
          [1].

          E02BDF can be used to determine the definite integrals of cubic
          spline fits and interpolants produced by E02BAF.

          4. References

          [1]   Cox M G (1975) An Algorithm for Spline Interpolation. J.
                Inst. Math. Appl. 15 95--108.

          5. Parameters

           1:  NCAP7 -- INTEGER                                       Input
                                    

               On entry: n+7, where n is the number of intervals of the
               spline (which is one greater than the number of interior
               knots, i.e., the knots strictly within the range a to b)
               over which the spline is defined. Constraint: NCAP7 >= 8.

           2:  LAMDA(NCAP7) -- DOUBLE PRECISION array                 Input
               On entry: LAMDA(j) must be set to the value of the jth
               member of the complete set of knots, (lambda)  for
                                                            j
                         

               j=1,2,...,n+7. Constraint: the LAMDA(j) must be in non-
               decreasing order with LAMDA(NCAP7-3) > LAMDA(4) and satisfy
                           LAMDA(1)=LAMDA(2)=LAMDA(3)=LAMDA(4)
               and

               LAMDA(NCAP7-3)=LAMDA(NCAP7-2)=LAMDA(NCAP7-1)=LAMDA(NCAP7).

           3:  C(NCAP7) -- DOUBLE PRECISION array                     Input
               On entry: the coefficient c  of the B-spline N (x), for
                                          i                  i
                         

               i=1,2,...,n+3. The remaining elements of the array are not
               used.

           4:  DEFINT -- DOUBLE PRECISION                            Output
               On exit: the value of the definite integral of s(x) between
               the limits x=a and x=b, where a=(lambda)  and b=(lambda)   .
                                                       4               n+4

           5:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          If on entry IFAIL = 0 or -1, explanatory error messages are
          output on the current error message unit (as defined by X04AAF).

          IFAIL= 1
               NCAP7 < 8, i.e., the number of intervals is not positive.

          IFAIL= 2
               At least one of the following restrictions on the knots is
               violated:
                    LAMDA(NCAP7-3) > LAMDA(4),

                    LAMDA(j) >= LAMDA(j-1),
               for j = 2,3,...,NCAP7, with equality in the cases
               j=2,3,4,NCAP7-2,NCAP7-1, and NCAP7.

          7. Accuracy

          The rounding errors are such that the computed value of the
          integral is exact for a slightly perturbed set of B-spline
          coefficients c  differing in a relative sense from those supplied
                        i      
          by no more than 2.2*(n+3)*machine precision.

          8. Further Comments

          The time taken by the routine is approximately proportional to
          

          n+7.

          9. Example

          Determine the definite integral over the interval 0<=x<=6 of a
          cubic spline having 6 interior knots at the positions (lambda)=1,
          3, 3, 3, 4, 4, the 8 additional knots 0, 0, 0, 0, 6, 6, 6, 6, and
          the 10 B-spline coefficients 10, 12, 13, 15, 22, 26, 24, 18, 14,
          12.

          The input data items (using the notation of Section 5) comprise
          the following values in the order indicated:

              

              n

              LAMDA(j) for j = 1,2,...,NCAP7
              ,

              C(j),    for j = 1,2,...,NCAP7-3

          The example program is written in a general form that will enable
          the definite integral of a cubic spline having an arbitrary
          number of knots to be computed. Any number of data sets may be
          supplied. The only changes required to the program relate to the
          dimensions of the arrays LAMDA and C.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02BEF
                  E02BEF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02BEF computes a cubic spline approximation to an arbitrary set
          of data points. The knots of the spline are located
          automatically, but a single parameter must be specified to
          control the trade-off between closeness of fit and smoothness of
          fit.

          2. Specification

                 SUBROUTINE E02BEF (START, M, X, Y, W, S, NEST, N, LAMDA,
                1                   C, FP, WRK, LWRK, IWRK, IFAIL)
                 INTEGER          M, NEST, N, LWRK, IWRK(NEST), IFAIL
                 DOUBLE PRECISION X(M), Y(M), W(M), S, LAMDA(NEST), C(NEST),
                1                 FP, WRK(LWRK)
                 CHARACTER*1      START

          3. Description

          This routine determines a smooth cubic spline approximation s(x)
          to the set of data points (x ,y ), with weights w , for
                                      r  r                 r
          r=1,2,...,m.

          The spline is given in the B-spline representation

                                      n-4
                                      --
                                s(x)= >  c N (x)                        (1)
                                      --  i i
                                      i=1

          where N (x) denotes the normalised cubic B-spline defined upon
                 i
          the knots (lambda) ,(lambda)   ,...,(lambda)   .
                            i         i+1             i+4

          The total number n of these knots and their values
          (lambda) ,...,(lambda)  are chosen automatically by the routine.
                  1             n
          The knots (lambda) ,...,(lambda)    are the interior knots; they
                            5             n-4
          divide the approximation interval [x ,x ] into n-7 sub-intervals.
                                              1  m
          The coefficients c ,c ,...,c    are then determined as the
                            1  2      n-4
          solution of the following constrained minimization problem:

          minimize

                                      n-4
                                      --        2
                               (eta)= >  (delta)                        (2)
                                      --        i
                                      i=5

          subject to the constraint

                                    m
                                    --          2
                           (theta)= >  (epsilon) <=S                    (3)
                                    --          r
                                    r=1

          where: (delta)    stands for the discontinuity jump in the third
                        i   order derivative of s(x) at the interior knot
                      (lambda) ,
                                    i

                 (epsilon)  denotes the weighted residual w (y -s(x )),
                          r                                r  r    r

          and    S          is a non-negative number to be specified by
                            the user.

          The quantity (eta) can be seen as a measure of the (lack of)
          smoothness of s(x), while closeness of fit is measured through
          (theta). By means of the parameter S, 'the smoothing factor', the
          user will then control the balance between these two (usually
          conflicting) properties. If S is too large, the spline will be
          too smooth and signal will be lost (underfit); if S is too small,
          the spline will pick up too much noise (overfit). In the extreme
          cases the routine will return an interpolating spline ((theta)=0)
          if S is set to zero, and the weighted least-squares cubic
          polynomial ((eta)=0) if S is set very large. Experimenting with S
          values between these two extremes should result in a good
          compromise. (See Section 8.2 for advice on choice of S.)

          The method employed is outlined in Section 8.3 and fully
          described in Dierckx [1], [2] and [3]. It involves an adaptive
          strategy for locating the knots of the cubic spline (depending on
          the function underlying the data and on the value of S), and an
          iterative method for solving the constrained minimization problem
          once the knots have been determined.

          Values of the computed spline, or of its derivatives or definite
          integral, can subsequently be computed by calling E02BBF, E02BCF
          or E02BDF, as described in Section 8.4.

          4. References

          [1]   Dierckx P (1975) An Algorithm for Smoothing, Differentiating
                and Integration of Experimental Data Using Spline Functions.
                J. Comput. Appl. Math. 1 165--184.

          [2]   Dierckx P (1982) A Fast Algorithm for Smoothing Data on a
                Rectangular Grid while using Spline Functions. SIAM J.
                Numer. Anal. 19 1286--1304.

          [3]   Dierckx P (1981) An Improved Algorithm for Curve Fitting
                with Spline Functions. Report TW54. Department of Computer
                Science, Katholieke Universiteit Leuven.

          [4]   Reinsch C H (1967) Smoothing by Spline Functions. Num. Math.
                10 177--183.

          5. Parameters

           1:  START -- CHARACTER*1                                   Input
               On entry: START must be set to 'C' or 'W'.

               If START = 'C' (Cold start), the routine will build up the
               knot set starting with no interior knots. No values need be
               assigned to the parameters N, LAMDA, WRK or IWRK.

               If START = 'W' (Warm start), the routine will restart the
               knot-placing strategy using the knots found in a previous
               call of the routine. In this case, the parameters N, LAMDA,
               WRK, and IWRK must be unchanged from that previous call.
               This warm start can save much time in searching for a
               satisfactory value of S. Constraint: START = 'C' or 'W'.

           2:  M -- INTEGER                                           Input
               On entry: m, the number of data points. Constraint: M >= 4.

           3:  X(M) -- DOUBLE PRECISION array                         Input
               On entry: the values x  of the independent variable
                                     r
               (abscissa) x, for r=1,2,...,m. Constraint: x <x <...<x
                                                           1  2      m

           4:  Y(M) -- DOUBLE PRECISION array                         Input
               On entry: the values y  of the dependent variable
                                     r
               (ordinate) y, for r=1,2,...,m.

           5:  W(M) -- DOUBLE PRECISION array                         Input
               On entry: the values w  of the weights, for r=1,2,...,m.
                                     r
               For advice on the choice of weights, see the Chapter
               Introduction, Section 2.1.2. Constraint: W(r) > 0, for
               r=1,2,...,m.

           6:  S -- DOUBLE PRECISION                                  Input
               On entry: the smoothing factor, S.

               If S=0.0, the routine returns an interpolating spline.

               If S is smaller than machine precision, it is assumed equal
               to zero.

               For advice on the choice of S, see Section 3 and Section 8.2
               Constraint: S >= 0.0.

           7:  NEST -- INTEGER                                        Input
               On entry: an over-estimate for the number, n, of knots
               required. Constraint: NEST >= 8. In most practical
               situations, NEST = M/2 is sufficient. NEST never needs to be
               larger than M + 4, the number of knots needed for
               interpolation (S = 0.0).

           8:  N -- INTEGER                                    Input/Output
               On entry: if the warm start option is used, the value of N
               must be left unchanged from the previous call. On exit: the
               total number, n, of knots of the computed spline.

           9:  LAMDA(NEST) -- DOUBLE PRECISION array           Input/Output
               On entry: if the warm start option is used, the values
               LAMDA(1), LAMDA(2),...,LAMDA(N) must be left unchanged from
               the previous call. On exit: the knots of the spline i.e.,
               the positions of the interior knots LAMDA(5), LAMDA(6),...
               ,LAMDA(N-4) as well as the positions of the additional knots
               LAMDA(1) = LAMDA(2) = LAMDA(3) = LAMDA(4) = x  and
                                                            1

               LAMDA(N-3) = LAMDA(N-2) = LAMDA(N-1) = LAMDA(N) = x  needed
                                                                  m
               for the B-spline representation.

          10:  C(NEST) -- DOUBLE PRECISION array                     Output
               On exit: the coefficient c  of the B-spline N (x) in the
                                          i                  i
               spline approximation s(x), for i=1,2,...,n-4.

          11:  FP -- DOUBLE PRECISION                                Output
               On exit: the sum of the squared weighted residuals, (theta),
               of the computed spline approximation. If FP = 0.0, this is
               an interpolating spline. FP should equal S within a relative
               tolerance of 0.001 unless n=8 when the spline has no
               interior knots and so is simply a cubic polynomial. For
               knots to be inserted, S must be set to a value below the
               value of FP produced in this case.

          12:  WRK(LWRK) -- DOUBLE PRECISION array                Workspace
               On entry: if the warm start option is used, the values WRK
               (1),...,WRK(n) must be left unchanged from the previous
               call.

          13:  LWRK -- INTEGER                                        Input
               On entry:
               the dimension of the array WRK as declared in the
               (sub)program from which E02BEF is called.
               Constraint: LWRK>=4*M+16*NEST+41.

          14:  IWRK(NEST) -- INTEGER array                        Workspace
               On entry: if the warm start option is used, the values IWRK
               (1), ..., IWRK(n) must be left unchanged from the previous
               call.

               This array is used as workspace.

          15:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          If on entry IFAIL = 0 or -1, explanatory error messages are
          output on the current error message unit (as defined by X04AAF).

          IFAIL= 1
               On entry START /= 'C' or 'W',

               or       M < 4,

               or       S < 0.0,

               or       S = 0.0 and NEST < M + 4,

               or       NEST < 8,

               or       LWRK<4*M+16*NEST+41.

          IFAIL= 2
               The weights are not all strictly positive.

          IFAIL= 3
               The values of X(r), for r=1,2,...,M, are not in strictly
               increasing order.

          IFAIL= 4
               The number of knots required is greater than NEST. Try
               increasing NEST and, if necessary, supplying larger arrays
               for the parameters LAMDA, C, WRK and IWRK. However, if NEST
               is already large, say NEST > M/2, then this error exit may
               indicate that S is too small.

          IFAIL= 5
               The iterative process used to compute the coefficients of
               the approximating spline has failed to converge. This error
               exit may occur if S has been set very small. If the error
               persists with increased S, consult NAG.

          If IFAIL = 4 or 5, a spline approximation is returned, but it
          fails to satisfy the fitting criterion (see (2) and (3) in
          Section 3) - perhaps by only a small amount, however.

          7. Accuracy

          On successful exit, the approximation returned is such that its
          weighted sum of squared residuals FP is equal to the smoothing
          factor S, up to a specified relative tolerance of 0.001 - except
          that if n=8, FP may be significantly less than S: in this case
          the computed spline is simply a weighted least-squares polynomial
          approximation of degree 3, i.e., a spline with no interior knots.

          8. Further Comments

          8.1. Timing

          The time taken for a call of E02BEF depends on the complexity of
          the shape of the data, the value of the smoothing factor S, and
          the number of data points. If E02BEF is to be called for
          different values of S, much time can be saved by setting START =

          8.2. Choice of S

          If the weights have been correctly chosen (see Section 2.1.2 of
          the Chapter Introduction), the standard deviation of w y  would
                                                                r r
          be the same for all r, equal to (sigma), say. In this case,
                                                              2      
          choosing the smoothing factor S in the range (sigma) (m+-\/2m),
          as suggested by Reinsch [4], is likely to give a good start in
          the search for a satisfactory value. Otherwise, experimenting
          with different values of S will be required from the start,
          taking account of the remarks in Section 3.

          In that case, in view of computation time and memory
          requirements, it is recommended to start with a very large value
          for S and so determine the least-squares cubic polynomial; the
          value returned for FP, call it FP , gives an upper bound for S.
                                           0
          Then progressively decrease the value of S to obtain closer fits
          - say by a factor of 10 in the beginning, i.e., S=FP /10, S=FP
                                                              0         0
          /100, and so on, and more carefully as the approximation shows
          more details.

          The number of knots of the spline returned, and their location,
          generally depend on the value of S and on the behaviour of the
          function underlying the data. However, if E02BEF is called with
          START = 'W', the knots returned may also depend on the smoothing
          factors of the previous calls. Therefore if, after a number of
          trials with different values of S and START = 'W', a fit can
          finally be accepted as satisfactory, it may be worthwhile to call
          E02BEF once more with the selected value for S but now using
          START = 'C'. Often, E02BEF then returns an approximation with the
          same quality of fit but with fewer knots, which is therefore
          better if data reduction is also important.

          8.3. Outline of Method Used

          If S=0, the requisite number of knots is known in advance, i.e.,
          n=m+4; the interior knots are located immediately as (lambda)  =
                                                                       i
          x   , for i=5,6,...,n-4. The corresponding least-squares spline
           i-2
          (see E02BAF) is then an interpolating spline and therefore a
          solution of the problem.

          If S>0, a suitable knot set is built up in stages (starting with
          no interior knots in the case of a cold start but with the knot
          set found in a previous call if a warm start is chosen). At each
          stage, a spline is fitted to the data by least-squares (see
          E02BAF) and (theta), the weighted sum of squares of residuals, is
          computed. If (theta)>S, new knots are added to the knot set to
          reduce (theta) at the next stage. The new knots are located in
          intervals where the fit is particularly poor, their number
          depending on the value of S and on the progress made so far in
          reducing (theta). Sooner or later, we find that (theta)<=S and at
          that point the knot set is accepted. The routine then goes on to
          compute the (unique) spline which has this knot set and which
          satisfies the full fitting criterion specified by (2) and (3).
          The theoretical solution has (theta)=S. The routine computes the
          spline by an iterative scheme which is ended when (theta)=S
          within a relative tolerance of 0.001. The main part of each
          iteration consists of a linear least-squares computation of
          special form, done in a similarly stable and efficient manner as
          in E02BAF.

          An exception occurs when the routine finds at the start that,
          even with no interior knots (n=8), the least-squares spline
          already has its weighted sum of squares of residuals <=S. In this
          case, since this spline (which is simply a cubic polynomial) also
          has an optimal value for the smoothness measure (eta), namely
          zero, it is returned at once as the (trivial) solution. It will
          usually mean that S has been chosen too large.

          For further details of the algorithm and its use, see Dierckx [3]

          8.4. Evaluation of Computed Spline

          The value of the computed spline at a given value X may be
          obtained in the double precision variable S by the call:


                 CALL E02BBF(N,LAMDA,C,X,S,IFAIL)

          where N, LAMDA and C are the output parameters of E02BEF.

          The values of the spline and its first three derivatives at a
          given value X may be obtained in the double precision array SDIF
          of dimension at least 4 by the call:

                 CALL E02BCF(N,LAMDA,C,X,LEFT,SDIF,IFAIL)

          where if LEFT = 1, left-hand derivatives are computed and if LEFT
          /= 1, right-hand derivatives are calculated. The value of LEFT is
          only relevant if X is an interior knot.

          The value of the definite integral of the spline over the
          interval X(1) to X(M) can be obtained in the double precision
          variable SINT by the call:

                 CALL E02BDF(N,LAMDA,C,SINT,IFAIL)

          9. Example

          This example program reads in a set of data values, followed by a
          set of values of S. For each value of S it calls E02BEF to
          compute a spline approximation, and prints the values of the
          knots and the B-spline coefficients c .
                                               i

          The program includes code to evaluate the computed splines, by
          calls to E02BBF, at the points x  and at points mid-way between
                                          r
          them. These values are not printed out, however; instead the
          results are illustrated by plots of the computed splines,
          together with the data points (indicated by *) and the positions
          of the knots (indicated by vertical lines): the effect of
          decreasing S can be clearly seen. (The plots were obtained by
          calling NAG Graphical Supplement routine J06FAF(*).)


                   Please see figures in printed Reference Manual

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02DAF
                  E02DAF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02DAF forms a minimal, weighted least-squares bicubic spline
          surface fit with prescribed knots to a given set of data points.

          2. Specification

                 SUBROUTINE E02DAF (M, PX, PY, X, Y, F, W, LAMDA, MU,
                1                   POINT, NPOINT, DL, C, NC, WS, NWS, EPS,
                2                   SIGMA, RANK, IFAIL)
                 INTEGER          M, PX, PY, POINT(NPOINT), NPOINT, NC, NWS,
                1                 RANK, IFAIL
                 DOUBLE PRECISION X(M), Y(M), F(M), W(M), LAMDA(PX), MU(PY),
                1                 DL(NC), C(NC), WS(NWS), EPS, SIGMA

          3. Description

          This routine determines a bicubic spline fit s(x,y) to the set of
          data points (x ,y ,f ) with weights w , for r=1,2,...,m. The two
                        r  r  r                r
          sets of internal knots of the spline, {(lambda)} and {(mu)},
          associated with the variables x and y respectively, are
          prescribed by the user. These knots can be thought of as dividing
          the data region of the (x,y) plane into panels (see diagram in
          Section 5). A bicubic spline consists of a separate bicubic
          polynomial in each panel, the polynomials joining together with
          continuity up to the second derivative across the panel
          boundaries.

          s(x,y) has the property that (Sigma), the sum of squares of its
          weighted residuals (rho) , for r=1,2,...,m, where
                                  r

                            (rho) =w (s(x ,y )-f ),                     (1)
                                 r  r    r  r   r

          is as small as possible for a bicubic spline with the given knot
          sets. The routine produces this minimized value of (Sigma) and
          the coefficients c   in the B-spline representation of s(x,y) -
                            ij
          see Section 8. E02DEF and E02DFF are available to compute values
          of the fitted spline from the coefficients c  .
                                                      ij

          The least-squares criterion is not always sufficient to determine
          the bicubic spline uniquely: there may be a whole family of
          splines which have the same minimum sum of squares. In these
          cases, the routine selects from this family the spline for which
          the sum of squares of the coefficients c   is smallest: in other
                                                  ij
          words, the minimal least-squares solution. This choice, although
          arbitrary, reduces the risk of unwanted fluctuations in the
          spline fit. The method employed involves forming a system of m
          linear equations in the coefficients c   and then computing its
                                                ij
          least-squares solution, which will be the minimal least-squares
          solution when appropriate. The basis of the method is described
          in Hayes and Halliday [4]. The matrix of the equation is formed
          using a recurrence relation for B-splines which is numerically
          stable (see Cox [1] and de Boor [2] - the former contains the
          more elementary derivation but, unlike [2], does not cover the
          case of coincident knots). The least-squares solution is also
          obtained in a stable manner by using orthogonal transformations,
          viz. a variant of Givens rotation (see Gentleman [3]). This
          requires only one row of the matrix to be stored at a time.
          Advantage is taken of the stepped-band structure which the matrix
          possesses when the data points are suitably ordered, there being
          at most sixteen non-zero elements in any row because of the
          definition of B-splines. First the matrix is reduced to upper
          triangular form and then the diagonal elements of this triangle
          are examined in turn. When an element is encountered whose
          square, divided by the mean squared weight, is less than a
          threshold (epsilon), it is replaced by zero and the rest of the
          elements in its row are reduced to zero by rotations with the
          remaining rows. The rank of the system is taken to be the number
          of non-zero diagonal elements in the final triangle, and the non-
          zero rows of this triangle are used to compute the minimal least-
          squares solution. If all the diagonal elements are non-zero, the
          rank is equal to the number of coefficients c   and the solution
                                                       ij
          obtained is the ordinary least-squares solution, which is unique
          in this case.

          4. References

          [1]   Cox M G (1972) The Numerical Evaluation of B-splines. J.
                Inst. Math. Appl. 10 134--149.

          [2]   De Boor C (1972) On Calculating with B-splines. J. Approx.
                Theory. 6 50--62.

          [3]   Gentleman W M (1973) Least-squares Computations by Givens
                Transformations without Square Roots. J. Inst. Math. Applic.
                12 329--336.

          [4]   Hayes J G and Halliday J (1974) The Least-squares Fitting of
                Cubic Spline Surfaces to General Data Sets. J. Inst. Math.
                Appl. 14 89--103.

          5. Parameters

           1:  M -- INTEGER                                           Input
               On entry: the number of data points, m. Constraint: M > 1.

           2:  PX -- INTEGER                                          Input

           3:  PY -- INTEGER                                          Input
               On entry: the total number of knots (lambda) and (mu)
               associated with the variables x and y, respectively.
               Constraint: PX >= 8 and PY >= 8.

               (They are such that PX-8 and PY-8 are the corresponding
               numbers of interior knots.) The running time and storage
               required by the routine are both minimized if the axes are
               labelled so that PY is the smaller of PX and PY.

           4:  X(M) -- DOUBLE PRECISION array                         Input

           5:  Y(M) -- DOUBLE PRECISION array                         Input

           6:  F(M) -- DOUBLE PRECISION array                         Input
               On entry: the co-ordinates of the data point (x ,y ,f ), for
                                                              r  r  r
               r=1,2,...,m. The order of the data points is immaterial, but
               see the array POINT, below.

           7:  W(M) -- DOUBLE PRECISION array                         Input
               On entry: the weight w  of the rth data point. It is
                                     r
               important to note the definition of weight implied by the
               equation (1) in Section 3, since it is also common usage to
               define weight as the square of this weight. In this routine,
               each w  should be chosen inversely proportional to the
                     r
               (absolute) accuracy of the corresponding f , as expressed,
                                                         r
               for example, by the standard deviation or probable error of
               the f . When the f  are all of the same accuracy, all the w
                    r            r                                        r
               may be set equal to 1.0.

           8:  LAMDA(PX) -- DOUBLE PRECISION array             Input/Output
               On entry: LAMDA(i+4) must contain the ith interior knot
               (lambda)     associated with the variable x, for
                       i+4
               i=1,2,...,PX-8. The knots must be in non-decreasing order
               and lie strictly within the range covered by the data values
               of x. A knot is a value of x at which the spline is allowed
               to be discontinuous in the third derivative with respect to
               x, though continuous up to the second derivative. This
               degree of continuity can be reduced, if the user requires,
               by the use of coincident knots, provided that no more than
               four knots are chosen to coincide at any point. Two, or
               three, coincident knots allow loss of continuity in,
               respectively, the second and first derivative with respect
               to x at the value of x at which they coincide. Four
               coincident knots split the spline surface into two
               independent parts. For choice of knots see Section 8. On
               exit: the interior knots LAMDA(5) to LAMDA(PX-4) are
               unchanged, and the segments LAMDA(1:4) and LAMDA(PX-3:PX)
               contain additional (exterior) knots introduced by the
               routine in order to define the full set of B-splines
               required. The four knots in the first segment are all set
               equal to the lowest data value of x and the other four
               additional knots are all set equal to the highest value:
               there is experimental evidence that coincident end-knots are
               best for numerical accuracy. The complete array must be left
               undisturbed if E02DEF or E02DFF is to be used subsequently.

           9:  MU(PY) -- DOUBLE PRECISION array                       Input
               On entry: MU(i+4) must contain the ith interior knot (mu)
                                                                        i+4
               associated with the variable y, i=1,2,...,PY-8. The same
               remarks apply to MU as to LAMDA above, with Y replacing X,
               and y replacing x.

          10:  POINT(NPOINT) -- INTEGER array                         Input
               On entry: indexing information usually provided by E02ZAF
               which enables the data points to be accessed in the order
               which produces the advantageous matrix structure mentioned
               in Section 3. This order is such that, if the (x,y) plane is
               thought of as being divided into rectangular panels by the
               two sets of knots, all data in a panel occur before data in
               succeeding panels, where the panels are numbered from bottom
               to top and then left to right with the usual arrangement of
               axes, as indicated in the diagram.

                      Please see figure in printed Reference Manual

               A data point lying exactly on one or more panel sides is
               considered to be in the highest numbered panel adjacent to
               the point. E02ZAF should be called to obtain the array
               POINT, unless it is provided by other means.

          11:  NPOINT -- INTEGER                                      Input
               On entry:
               the dimension of the array POINT as declared in the
               (sub)program from which E02DAF is called.
               Constraint: NPOINT >= M + (PX-7)*(PY-7).

          12:  DL(NC) -- DOUBLE PRECISION array                      Output
               On exit: DL gives the squares of the diagonal elements of
               the reduced triangular matrix, divided by the mean squared
               weight. It includes those elements, less than (epsilon),
               which are treated as zero (see Section 3).

          13:  C(NC) -- DOUBLE PRECISION array                       Output
               On exit: C gives the coefficients of the fit. C((PY-4)*(i-
               1)+j) is the coefficient c   of Section 3 and Section 8 for
                                         ij
               i=1,2,...,PX-4 and j=1,2,...,PY-4. These coefficients are
               used by E02DEF or E02DFF to calculate values of the fitted
               function.

          14:  NC -- INTEGER                                          Input
               On entry: the value (PX-4)*(PY-4).

          15:  WS(NWS) -- DOUBLE PRECISION array                  Workspace

          16:  NWS -- INTEGER                                         Input
               On entry:
               the dimension of the array WS as declared in the
               (sub)program from which E02DAF is called.
               Constraint: NWS>=(2*NC+1)*(3*PY-6)-2.

          17:  EPS -- DOUBLE PRECISION                                Input
               On entry: a threshold (epsilon) for determining the
               effective rank of the system of linear equations. The rank
               is determined as the number of elements of the array DL (see
               below) which are non-zero. An element of DL is regarded as
               zero if it is less than (epsilon). Machine precision is a
               suitable value for (epsilon) in most practical applications
               which have only 2 or 3 decimals accurate in data. If some
               coefficients of the fit prove to be very large compared with
               the data ordinates, this suggests that (epsilon) should be
               increased so as to decrease the rank. The array DL will give
               a guide to appropriate values of (epsilon) to achieve this,
               as well as to the choice of (epsilon) in other cases where
               some experimentation may be needed to determine a value
               which leads to a satisfactory fit.

          18:  SIGMA -- DOUBLE PRECISION                             Output
               On exit: (Sigma), the weighted sum of squares of residuals.
               This is not computed from the individual residuals but from
               the right-hand sides of the orthogonally-transformed linear
               equations. For further details see Hayes and Halliday [4]
               page 97. The two methods of computation are theoretically
               equivalent, but the results may differ because of rounding
               error.

          19:  RANK -- INTEGER                                       Output
               On exit: the rank of the system as determined by the value
               of the threshold (epsilon). When RANK = NC, the least-
               squares solution is unique: in other cases the minimal
               least-squares solution is computed.

          20:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               At least one set of knots is not in non-decreasing order, or
               an interior knot is outside the range of the data values.

          IFAIL= 2
               More than four knots coincide at a single point, possibly
               because all data points have the same value of x (or y) or
               because an interior knot coincides with an extreme data
               value.

          IFAIL= 3
               Array POINT does not indicate the data points in panel
               order. Call E02ZAF to obtain a correct array.

          IFAIL= 4
               On entry M <= 1,

               or       PX < 8,

               or       PY < 8,

               or       NC /= (PX-4)*(PY-4),

               or       NWS is too small,

               or       NPOINT is too small.

          IFAIL= 5
               All the weights w  are zero or rank determined as zero.
                                r

          7. Accuracy

          The computation of the B-splines and reduction of the observation
          matrix to triangular form are both numerically stable.

          8. Further Comments

          The time taken by this routine is approximately proportional to
                                                           2
          the number of data points, m, and to (3*(PY-4)+4) .

          The B-spline representation of the bicubic spline is

                                       --
                               s(x,y)= > c  M (x)N (y)
                                       -- ij i    j
                                       ij

          summed over i=1,2,...,PX-4 and over j=1,2,...,PY-4. Here M (x)
                                                                    i
          and N (y) denote normalised cubic B-splines,the former defined on
               j
          the knots (lambda) ,(lambda)   ,...,(lambda)    and the latter on
                            i         i+1             i+4
          the knots (mu) ,(mu)   ,...,(mu)   . For further details, see
                        j     j+1         j+4
          Hayes and Halliday [4] for bicubic splines and de Boor [2] for
          normalised B-splines.

          The choice of the interior knots, which help to determine the
          spline's shape, must largely be a matter of trial and error. It
          is usually best to start with a small number of knots and,
          examining the fit at each stage, add a few knots at a time at
          places where the fit is particularly poor. In intervals of x or y
          where the surface represented by the data changes rapidly, in
          function value or derivatives, more knots will be needed than
          elsewhere. In some cases guidance can be obtained by analogy with
          the case of coincident knots: for example, just as three
          coincident knots can produce a discontinuity in slope, three
          close knots can produce rapid change in slope. Of course, such
          rapid changes in behaviour must be adequately represented by the
          data points, as indeed must the behaviour of the surface
          generally, if a satisfactory fit is to be achieved. When there is
          no rapid change in behaviour, equally-spaced knots will often
          suffice.

          In all cases the fit should be examined graphically before it is
          accepted as satisfactory.

          The fit obtained is not defined outside the rectangle

                  (lambda) <=x<=(lambda)    ,   (mu) <=y<=(mu)
                          4             PX-3        4         PY-3

          The reason for taking the extreme data values of x and y for
          these four knots is that, as is usual in data fitting, the fit
          cannot be expected to give satisfactory values outside the data
          region. If, nevertheless, the user requires values over a larger
          rectangle, this can be achieved by augmenting the data with two
          artificial data points (a,c,0) and (b,d,0) with zero weight,
          where a<=x<=b, c<=y<=d defines the enlarged rectangle. In the
          case when the data are adequate to make the least-squares
          solution unique (RANK = NC), this enlargement will not affect the
          fit over the original rectangle, except for possibly enlarged
          rounding errors, and will simply continue the bicubic polynomials
          in the panels bordering the rectangle out to the new boundaries:
          in other cases the fit will be affected. Even using the original
          rectangle there may be regions within it, particularly at its
          corners, which lie outside the data region and where, therefore,
          the fit will be unreliable. For example, if there is no data
          point in panel 1 of the diagram in Section 5, the least-squares
          criterion leaves the spline indeterminate in this panel: the
          minimal spline determined by the subroutine in this case passes
          through the value zero at the point ((lambda) ,(mu) ).
                                                       4     4

          9. Example

          This example program reads a value for (epsilon), and a set of
          data points, weights and knot positions. If there are more y
          knots than x knots, it interchanges the x and y axes. It calls
          E02ZAF to sort the data points into panel order, E02DAF to fit a
          bicubic spline to them, and E02DEF to evaluate the spline at the
          data points.

          Finally it prints:

               the weighted sum of squares of residuals computed from the
               linear equations;

               the rank determined by E02DAF;

               data points, fitted values and residuals in panel order;

               the weighted sum of squares of the residuals;

               the coefficients of the spline fit.

          The program is written to handle any number of data sets.

          Note: the data supplied in this example is not typical of a
          realistic problem: the number of data points would normally be
          much larger (in which case the array dimensions and the value of
          NWS in the program would have to be increased); and the value of
          (epsilon) would normally be much smaller on most machines (see
                                                     -6
          Section 5; the relatively large value of 10   has been chosen in
          order to illustrate a minimal least-squares solution when RANK <
          NC; in this example NC = 24).

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02DCF
                  E02DCF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02DCF computes a bicubic spline approximation to a set of data
          values, given on a rectangular grid in the x-y plane. The knots
          of the spline are located automatically, but a single parameter
          must be specified to control the trade-off between closeness of
          fit and smoothness of fit.

          2. Specification

                 SUBROUTINE E02DCF (START, MX, X, MY, Y, F, S, NXEST,
                1                   NYEST, NX, LAMDA, NY, MU, C, FP, WRK,
                2                   LWRK, IWRK, LIWRK, IFAIL)
                 INTEGER          MX, MY, NXEST, NYEST, NX, NY, LWRK, IWRK
                1                 (LIWRK), LIWRK, IFAIL
                 DOUBLE PRECISION X(MX), Y(MY), F(MX*MY), S, LAMDA(NXEST),
                1                 MU(NYEST), C((NXEST-4)*(NYEST-4)), FP, WRK
                2                 (LWRK)
                 CHARACTER*1      START

          3. Description

          This routine determines a smooth bicubic spline approximation
          s(x,y) to the set of data points (x ,y ,f   ), for q=1,2,...,m
                                             q  r  q,r                  x
          and r=1,2,...,m .
                         y

          The spline is given in the B-spline representation

                                n -4 n -4
                                 x    y
                                --   --
                        s(x,y)= >    >   c  M (x)N (y),                 (1)
                                --   --   ij i    j
                                i=1  j=1

          where M (x) and N (y) denote normalised cubic B-splines, the
                 i         j
          former defined on the knots (lambda)  to (lambda)    and the
                                              i            i+4
          latter on the knots (mu)  to (mu)   . For further details, see
                                  j        j+4
          Hayes and Halliday [4] for bicubic splines and de Boor [1] for
          normalised B-splines.

          The total numbers n  and n  of these knots and their values
                             x      y
          (lambda) ,...,(lambda)   and (mu) ,...,(mu)   are chosen
                  1             n          1         n
                                 x                    y
          automatically by the routine. The knots (lambda) ,...,
                                                          5
          (lambda)     and (mu) ,...,(mu)     are the interior knots; they
                  n -4         5         n -4
                   x                      y
          divide the approximation domain [x ,x  ]*[y ,y  ] into (
                                            1  m     1  m
                                               m        m
          n -7)*(n -7) subpanels [(lambda) ,(lambda)   ]*[(mu) ,(mu)   ],
           x      y                       i         i+1       j     j+1
          for i=4,5,...,n -4, j=4,5,...,n -4. Then, much as in the curve
                         x               y
          case (see E02BEF), the coefficients c   are determined as the
                                               ij
          solution of the following constrained minimization problem:

          minimize

                                     (eta),                             (2)

          subject to the constraint

                                 m   m
                                  x   y
                                 --  --          2
                        (theta)= >   >  (epsilon)   <=S,                (3)
                                 --  --          q,r
                                 q=1 r=1

          where  (eta) is a measure of the (lack of) smoothness of s(x,y).
                       Its value depends on the discontinuity jumps in
                       s(x,y) across the boundaries of the subpanels. It is
                       zero only when there are no discontinuities and is
                       positive otherwise, increasing with the size of the
                       jumps (see Dierckx [2] for details).

                 (epsilon)    denotes the residual f   -s(x ,y ),
                          q,r                       q,r    q  r

          and    S    is a non-negative number to be specified by the user.

          By means of the parameter S, 'the smoothing factor', the user
          will then control the balance between smoothness and closeness of
          fit, as measured by the sum of squares of residuals in (3). If S
          is too large, the spline will be too smooth and signal will be
          lost (underfit); if S is too small, the spline will pick up too
          much noise (overfit). In the extreme cases the routine will
          return an interpolating spline ((theta)=0) if S is set to zero,
          and the least-squares bicubic polynomial ((eta)=0) if S is set
          very large. Experimenting with S-values between these two
          extremes should result in a good compromise. (See Section 8.3 for
          advice on choice of S.)

          The method employed is outlined in Section 8.5 and fully
          described in Dierckx [2] and [3]. It involves an adaptive
          strategy for locating the knots of the bicubic spline (depending
          on the function underlying the data and on the value of S), and
          an iterative method for solving the constrained minimization
          problem once the knots have been determined.

          Values of the computed spline can subsequently be computed by
          calling E02DEF or E02DFF as described in Section 8.6.

          4. References

          [1]   De Boor C (1972) On Calculating with B-splines. J. Approx.
                Theory. 6 50--62.

          [2]   Dierckx P (1982) A Fast Algorithm for Smoothing Data on a
                Rectangular Grid while using Spline Functions. SIAM J.
                Numer. Anal. 19 1286--1304.

          [3]   Dierckx P (1981) An Improved Algorithm for Curve Fitting
                with Spline Functions. Report TW54. Department of Computer
                Science, Katholieke Universiteit Leuven.

          [4]   Hayes J G and Halliday J (1974) The Least-squares Fitting of
                Cubic Spline Surfaces to General Data Sets. J. Inst. Math.
                Appl. 14 89--103.

          [5]   Reinsch C H (1967) Smoothing by Spline Functions. Num. Math.
                10 177--183.

          5. Parameters

           1:  START -- CHARACTER*1                                   Input
               On entry: START must be set to 'C' or 'W'.

               If START = 'C' (Cold start), the routine will build up the
               knot set starting with no interior knots. No values need be
               assigned to the parameters NX, NY, LAMDA, MU, WRK or IWRK.

               If START = 'W' (Warm start), the routine will restart the
               knot-placing strategy using the knots found in a previous
               call of the routine. In this case, the parameters NX, NY,
               LAMDA, MU, WRK and IWRK must be unchanged from that previous
               call. This warm start can save much time in searching for a
               satisfactory value of S. Constraint: START = 'C' or 'W'.

           2:  MX -- INTEGER                                          Input
               On entry: m , the number of grid points along the x axis.
                          x
               Constraint: MX >= 4.

           3:  X(MX) -- DOUBLE PRECISION array                        Input
               On entry: X(q) must be set to x , the x co-ordinate of the
                                              q
               qth grid point along the x axis, for q=1,2,...,m .
                                                               x
               Constraint: x <x <...<x  .
                            1  2      m
                                       x

           4:  MY -- INTEGER                                          Input
               On entry: m , the number of grid points along the y axis.
                          y
               Constraint: MY >= 4.

           5:  Y(MY) -- DOUBLE PRECISION array                        Input
               On entry: Y(r) must be set to y , the y co-ordinate of the
                                              r
               rth grid point along the y axis, for r=1,2,...,m .
                                                               y
               Constraint: y <y <...<y  .
                            1  2      m
                                       y

           6:  F(MX*MY) -- DOUBLE PRECISION array                     Input
               On entry: F(m *(q-1)+r) must contain the data value f   ,
                            y                                       q,r
               for q=1,2,...,m  and r=1,2,...,m .
                              x                y

           7:  S -- DOUBLE PRECISION                                  Input
               On entry: the smoothing factor, S.

               If S=0.0, the routine returns an interpolating spline.

               If S is smaller than machine precision, it is assumed equal
               to zero.

               For advice on the choice of S, see Section 3 and Section 8.3
               Constraint: S >= 0.0.

           8:  NXEST -- INTEGER                                       Input

           9:  NYEST -- INTEGER                                       Input
               On entry: an upper bound for the number of knots n  and n
                                                                  x      y
               required in the x- and y-directions respectively.

               In most practical situations, NXEST =m /2 and NYEST m /2 is
                                                     x              y
               sufficient. NXEST and NYEST never need to be larger than
               m +4 and m +4 respectively, the numbers of knots needed for
                x        y
               interpolation (S=0.0). See also Section 8.4. Constraint:
               NXEST >= 8 and NYEST >= 8.

          10:  NX -- INTEGER                                   Input/Output
               On entry: if the warm start option is used, the value of NX
               must be left unchanged from the previous call. On exit: the
               total number of knots, n , of the computed spline with
                                       x
               respect to the x variable.

          11:  LAMDA(NXEST) -- DOUBLE PRECISION array          Input/Output
               On entry: if the warm start option is used, the values
               LAMDA(1), LAMDA(2),...,LAMDA(NX) must be left unchanged from
               the previous call. On exit: LAMDA contains the complete set
               of knots (lambda)  associated with the x variable, i.e., the
                                i
               interior knots LAMDA(5), LAMDA(6), ..., LAMDA(NX-4) as well
               as the additional knots LAMDA(1) = LAMDA(2) = LAMDA(3) =
               LAMDA(4) = X(1) and LAMDA(NX-3) = LAMDA(NX-2) = LAMDA(NX-1)
               = LAMDA(NX) = X(MX) needed for the B-spline representation.

          12:  NY -- INTEGER                                   Input/Output
               On entry: if the warm start option is used, the value of NY
               must be left unchanged from the previous call. On exit: the
               total number of knots, n , of the computed spline with
                                       y
               respect to the y variable.

          13:  MU(NYEST) -- DOUBLE PRECISION array             Input/Output
               On entry: if the warm start option is used, the values MU
               (1), MU(2),...,MU(NY) must be left unchanged from the
               previous call. On exit: MU contains the complete set of
               knots (mu)  associated with the y variable, i.e., the
                         i
               interior knots MU(5), MU(6),...,MU(NY-4) as well as the
               additional knots MU(1) = MU(2) = MU(3) = MU(4) = Y(1) and MU
               (NY-3) = MU(NY-2) = MU(NY-1) = MU(NY) = Y(MY) needed for the
               B-spline representation.

          14:  C((NXEST-4)*(NYEST-4)) -- DOUBLE PRECISION array      Output
               On exit: the coefficients of the spline approximation. C(
               (n -4)*(i-1)+j) is the coefficient c   defined in Section 3.
                 y                                 ij

          15:  FP -- DOUBLE PRECISION                                Output
               On exit: the sum of squared residuals, (theta), of the
               computed spline approximation. If FP = 0.0, this is an
               interpolating spline. FP should equal S within a relative
               tolerance of 0.001 unless NX = NY = 8, when the spline has
               no interior knots and so is simply a bicubic polynomial. For
               knots to be inserted, S must be set to a value below the
               value of FP produced in this case.

          16:  WRK(LWRK) -- DOUBLE PRECISION array                Workspace
               On entry: if the warm start option is used, the values WRK
               (1),...,WRK(4) must be left unchanged from the previous
               call.

               This array is used as workspace.

          17:  LWRK -- INTEGER                                        Input
               On entry:
               the dimension of the array WRK as declared in the
               (sub)program from which E02DCF is called.
               Constraint:
                    LWRK>=4*(MX+MY)+11*(NXEST+NYEST)+NXEST*MY

                          +max(MY,NXEST)+54.

          18:  IWRK(LIWRK) -- INTEGER array                       Workspace
               On entry: if the warm start option is used, the values IWRK
               (1), ..., IWRK(3) must be left unchanged from the previous
               call.

               This array is used as workspace.

          19:  LIWRK -- INTEGER                                       Input
               On entry:
               the dimension of the array IWRK as declared in the
               (sub)program from which E02DCF is called.
               Constraint: LIWRK >= 3 + MX + MY + NXEST + NYEST.

          20:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          If on entry IFAIL = 0 or -1, explanatory error messages are
          output on the current error message unit (as defined by X04AAF).

          IFAIL= 1
               On entry START /= 'C' or 'W',

               or       MX < 4,

               or       MY < 4,

               or       S < 0.0,

               or       S = 0.0 and NXEST < MX + 4,

               or       S = 0.0 and NYEST < MY + 4,

               or       NXEST < 8,

               or       NYEST < 8,

               or       LWRK < 4*(MX+MY)+11*(NXEST+NYEST)+NXEST*MY+
                               +max(MY,NXEST)+54

               or       LIWRK < 3 + MX + MY + NXEST + NYEST.

          IFAIL= 2
               The values of X(q), for q = 1,2,...,MX, are not in strictly
               increasing order.

          IFAIL= 3
               The values of Y(r), for r = 1,2,...,MY, are not in strictly
               increasing order.

          IFAIL= 4
               The number of knots required is greater than allowed by
               NXEST and NYEST. Try increasing NXEST and/or NYEST and, if
               necessary, supplying larger arrays for the parameters LAMDA,
               MU, C, WRK and IWRK. However, if NXEST and NYEST are already
               large, say NXEST > MX/2 and NYEST > MY/2, then this error
               exit may indicate that S is too small.

          IFAIL= 5
               The iterative process used to compute the coefficients of
               the approximating spline has failed to converge. This error
               exit may occur if S has been set very small. If the error
               persists with increased S, consult NAG.

          If IFAIL = 4 or 5, a spline approximation is returned, but it
          fails to satisfy the fitting criterion (see (2) and (3) in
          Section 3) -- perhaps by only a small amount, however.

          7. Accuracy

          On successful exit, the approximation returned is such that its
          sum of squared residuals FP is equal to the smoothing factor S,
          up to a specified relative tolerance of 0.001 - except that if
          n =8 and n =8, FP may be significantly less than S: in this case
           x        y
          the computed spline is simply the least-squares bicubic
          polynomial approximation of degree 3, i.e., a spline with no
          interior knots.

          8. Further Comments

          8.1. Timing

          The time taken for a call of E02DCF depends on the complexity of
          the shape of the data, the value of the smoothing factor S, and
          the number of data points. If E02DCF is to be called for
          different values of S, much time can be saved by setting START =

          8.2. Weighting of Data Points

          E02DCF does not allow individual weighting of the data values. If
          these were determined to widely differing accuracies, it may be
          better to use E02DDF. The computation time would be very much
          longer, however.

          8.3. Choice of S

          If the standard deviation of f    is the same for all q and r
                                        q,r
          (the case for which this routine is designed - see Section 8.2.)
          and known to be equal, at least approximately, to (sigma), say,
          then following Reinsch [5] and choosing the smoothing factor S in
                           2      
          the range (sigma) (m+-\/2m), where m=m m , is likely to give a
                                                x y
          good start in the search for a satisfactory value. If the
          standard deviations vary, the sum of their squares over all the
          data points could be used. Otherwise experimenting with different
          values of S will be required from the start, taking account of
          the remarks in Section 3.

          In that case, in view of computation time and memory
          requirements, it is recommended to start with a very large value
          for S and so determine the least-squares bicubic polynomial; the
          value returned for FP, call it FP , gives an upper bound for S.
                                           0
          Then progressively decrease the value of S to obtain closer fits
          - say by a factor of 10 in the beginning, i.e., S=FP /10,
                                                              0
          S=FP /100, and so on, and more carefully as the approximation
              0
          shows more details.

          The number of knots of the spline returned, and their location,
          generally depend on the value of S and on the behaviour of the
          function underlying the data. However, if E02DCF is called with
          START = 'W', the knots returned may also depend on the smoothing
          factors of the previous calls. Therefore if, after a number of
          trials with different values of S and START = 'W', a fit can
          finally be accepted as satisfactory, it may be worthwhile to call
          E02DCF once more with the selected value for S but now using
          START = 'C'. Often, E02DCF then returns an approximation with the
          same quality of fit but with fewer knots, which is therefore
          better if data reduction is also important.

          8.4. Choice of NXEST and NYEST

          The number of knots may also depend on the upper bounds NXEST and
          NYEST. Indeed, if at a certain stage in E02DCF the number of
          knots in one direction (say n ) has reached the value of its
                                       x
          upper bound (NXEST), then from that moment on all subsequent
          knots are added in the other (y) direction. Therefore the user
          has the option of limiting the number of knots the routine
          locates in any direction. For example, by setting NXEST = 8 (the
          lowest allowable value for NXEST), the user can indicate that he
          wants an approximation which is a simple cubic polynomial in the
          variable x.

          8.5. Outline of Method Used

          If S=0, the requisite number of knots is known in advance, i.e.,
          n =m +4 and n =m +4; the interior knots are located immediately
           x  x        y  y
          as (lambda)  = x    and (mu)  = y   , for i=5,6,...,n -4 and
                     i    i-2         j    j-2                 x
          j=5,6,...,n -4. The corresponding least-squares spline is then an
                     y
          interpolating spline and therefore a solution of the problem.

          If S>0, suitable knot sets are built up in stages (starting with
          no interior knots in the case of a cold start but with the knot
          set found in a previous call if a warm start is chosen). At each
          stage, a bicubic spline is fitted to the data by least-squares,
          and (theta), the sum of squares of residuals, is computed. If
          (theta)>S, new knots are added to one knot set or the other so as
          to reduce (theta) at the next stage. The new knots are located in
          intervals where the fit is particularly poor, their number
          depending on the value of S and on the progress made so far in
          reducing (theta). Sooner or later, we find that (theta)<=S and at
          that point the knot sets are accepted. The routine then goes on
          to compute the (unique) spline which has these knot sets and
          which satisfies the full fitting criterion specified by (2) and
          (3). The theoretical solution has (theta)=S. The routine computes
          the spline by an iterative scheme which is ended when (theta)=S
          within a relative tolerance of 0.001. The main part of each
          iteration consists of a linear least-squares computation of
          special form, done in a similarly stable and efficient manner as
          in E02BAF for least-squares curve fitting.

          An exception occurs when the routine finds at the start that,
          even with no interior knots (n =n =8), the least-squares spline
                                        x  y
          already has its sum of residuals <=S. In this case, since this
          spline (which is simply a bicubic polynomial) also has an optimal
          value for the smoothness measure (eta), namely zero, it is
          returned at once as the (trivial) solution. It will usually mean
          that S has been chosen too large.

          For further details of the algorithm and its use see Dierckx [2].

          8.6. Evaluation of Computed Spline

          The values of the computed spline at the points (TX(r),TY(r)),
          for r = 1,2,...,N, may be obtained in the double precision array
          FF, of length at least N, by the following code:

                 IFAIL = 0
                 CALL E02DEF(N,NX,NY,TX,TY,LAMDA,MU,C,FF,WRK,IWRK,IFAIL)

          where NX, NY, LAMDA, MU and C are the output parameters of E02DCF
          , WRK is a double precision workspace array of length at least
          NY-4, and IWRK is an integer workspace array of length at least
          NY-4.

          To evaluate the computed spline on a KX by KY rectangular grid of
          points in the x-y plane, which is defined by the x co-ordinates
          stored in TX(q), for q=1,2,...,KX, and the y co-ordinates stored
          in TY(r), for r=1,2,...,KY, returning the results in the double
          precision array FG which is of length at least KX*KY, the
          following call may be used:

                IFAIL = 0
                CALL E02DFF(KX,KY,NX,NY,TX,TY,LAMDA,MU,C,FG,WRK,LWRK,
               *            IWRK,LIWRK,IFAIL)

          where NX, NY, LAMDA, MU and C are the output parameters of E02DCF
          , WRK is a double precision workspace array of length at least
          LWRK = min(NWRK1,NWRK2), NWRK1 = KX*4+NX, NWRK2 = KY*4+NY, and
          IWRK is an integer workspace array of length at least LIWRK = KY
          + NY - 4 if NWRK1 >= NWRK2, or KX + NX - 4 otherwise. The result
          of the spline evaluated at grid point (q,r) is returned in
          element (KY*(q-1)+r) of the array FG.

          9. Example

          This example program reads in values of MX, MY, x , for q = 1,2,.
                                                           q
                      r
          ordinates f    defined at the grid points (x ,y ). It then calls
                     q,r                              q  r
          E02DCF to compute a bicubic spline approximation for one
          specified value of S, and prints the values of the computed knots
          and B-spline coefficients. Finally it evaluates the spline at a
          small sample of points on a rectangular grid.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02DDF
                  E02DDF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02DDF computes a bicubic spline approximation to a set of
          scattered data. The knots of the spline are located
          automatically, but a single parameter must be specified to
          control the trade-off between closeness of fit and smoothness of
          fit.

          2. Specification

                 SUBROUTINE E02DDF (START, M, X, Y, F, W, S, NXEST, NYEST,
                1                   NX, LAMDA, NY, MU, C, FP, RANK, WRK,
                2                   LWRK, IWRK, LIWRK, IFAIL)
                 INTEGER          M, NXEST, NYEST, NX, NY, RANK, LWRK, IWRK
                1                 (LIWRK), LIWRK, IFAIL
                 DOUBLE PRECISION X(M), Y(M), F(M), W(M), S, LAMDA(NXEST),
                1                 MU(NYEST), C((NXEST-4)*(NYEST-4)), FP, WRK
                2                 (LWRK)
                 CHARACTER*1      START

          3. Description

          This routine determines a smooth bicubic spline approximation
          s(x,y) to the set of data points (x ,y ,f ) with weights w , for
                                             r  r  r                r
          r=1,2,...,m.

          The approximation domain is considered to be the rectangle
          [x   ,x   ]*[y   ,y   ], where x    (y   ) and x    (y   ) denote
            min  max    min  max          min   min       max   max
          the lowest and highest data values of x (y).

          The spline is given in the B-spline representation

                                n -4 n -4
                                 x    y
                                --   --
                        s(x,y)= >    >   c  M (x)N (y),                 (1)
                                --   --   ij i    j
                                i=1  j=1

          where M (x) and N (y) denote normalised cubic B-splines, the
                 i         j
          former defined on the knots (lambda)  to (lambda)    and the
                                              i            i+4
          latter on the knots (mu)  to (mu)   . For further details, see
                                  j        j+4
          Hayes and Halliday [4] for bicubic splines and de Boor [1] for
          normalised B-splines.

          The total numbers n  and n  of these knots and their values
                             x      y
          (lambda) ,...,(lambda)   and (mu) ,...,(mu)   are chosen
                  1             n          1         n
                                 x                    y
          automatically by the routine. The knots (lambda) ,...,
                                                          5
          (lambda)     and (mu) ,..., (mu)     are the interior knots; they
                  n -4         5          n -4
                   x                       y
          divide the approximation domain [x   ,x   ]*[y   ,y   ] into (
                                            min  max    min  max
          n -7)*(n -7) subpanels [(lambda) ,(lambda)   ]*[(mu) ,(mu)   ],
           x      y                       i         i+1       j     j+1
          for i=4,5,...,n -4; j=4,5,...,n -4. Then, much as in the curve
                         x               y
          case (see E02BEF), the coefficients c   are determined as the
                                               ij
          solution of the following constrained minimization problem:

          minimize

                                     (eta),                             (2)

          subject to the constraint

                                    m
                                    --          2
                           (theta)= >  (epsilon) <=S                    (3)
                                    --          r
                                    r=1

          where: (eta) is a measure of the (lack of) smoothness of s(x,y).
                       Its value depends on the discontinuity jumps in
                       s(x,y) across the boundaries of the subpanels. It is
                       zero only when there are no discontinuities and is
                       positive otherwise, increasing with the size of the
                       jumps (see Dierckx [2] for details).

                 (epsilon)  denotes the weighted residual w (f -s(x ,y )),
                          r                                r  r    r  r

          and    S     is a non-negative number to be specified by the user.

          By means of the parameter S, 'the smoothing factor', the user
          will then control the balance between smoothness and closeness of
          fit, as measured by the sum of squares of residuals in (3). If S
          is too large, the spline will be too smooth and signal will be
          lost (underfit); if S is too small, the spline will pick up too
          much noise (overfit). In the extreme cases the method would
          return an interpolating spline ((theta)=0) if S were set to zero,
          and returns the least-squares bicubic polynomial ((eta)=0) if S
          is set very large. Experimenting with S-values between these two
          extremes should result in a good compromise. (See Section 8.2 for
          advice on choice of S.) Note however, that this routine, unlike
          E02BEF and E02DCF, does not allow S to be set exactly to zero: to
          compute an interpolant to scattered data, E01SAF or E01SEF should
          be used.

          The method employed is outlined in Section 8.5 and fully
          described in Dierckx [2] and [3]. It involves an adaptive
          strategy for locating the knots of the bicubic spline (depending
          on the function underlying the data and on the value of S), and
          an iterative method for solving the constrained minimization
          problem once the knots have been determined.

          Values of the computed spline can subsequently be computed by
          calling E02DEF or E02DFF as described in Section 8.6.

          4. References

          [1]   De Boor C (1972) On Calculating with B-splines. J. Approx.
                Theory. 6 50--62.

          [2]   Dierckx P (1981) An Algorithm for Surface Fitting with
                Spline Functions. IMA J. Num. Anal. 1 267--283.

          [3]   Dierckx P (1981) An Improved Algorithm for Curve Fitting
                with Spline Functions. Report TW54. Department of Computer
                Science, Katholieke Universiteit Leuven.

          [4]   Hayes J G and Halliday J (1974) The Least-squares Fitting of
                Cubic Spline Surfaces to General Data Sets. J. Inst. Math.
                Appl. 14 89--103.

          [5]   Peters G and Wilkinson J H (1970) The Least-squares Problem
                and Pseudo-inverses. Comput. J. 13 309--316.

          [6]   Reinsch C H (1967) Smoothing by Spline Functions. Num. Math.
                10 177--183.

          5. Parameters

           1:  START -- CHARACTER*1                                   Input
               On entry: START must be set to 'C' or 'W'.

               If START = 'C' (Cold start), the routine will build up the
               knot set starting with no interior knots. No values need be
               assigned to the parameters NX, NY, LAMDA, MU or WRK.

               If START = 'W' (Warm start), the routine will restart the
               knot-placing strategy using the knots found in a previous
               call of the routine. In this case, the parameters NX, NY,
               LAMDA, MU and WRK must be unchanged from that previous call.
               This warm start can save much time in searching for a
               satisfactory value of S. Constraint: START = 'C' or 'W'.

           2:  M -- INTEGER                                           Input
               On entry: m, the number of data points.

               The number of data points with non-zero weight (see W below)
               must be at least 16.

           3:  X(M) -- DOUBLE PRECISION array                         Input

           4:  Y(M) -- DOUBLE PRECISION array                         Input

           5:  F(M) -- DOUBLE PRECISION array                         Input
               On entry: X(r), Y(r), F(r) must be set to the co-ordinates
               of (x ,y ,f ), the rth data point, for r=1,2,...,m. The
                    r  r  r
               order of the data points is immaterial.

           6:  W(M) -- DOUBLE PRECISION array                         Input
               On entry: W(r) must be set to w , the rth value in the set
                                              r
               of weights, for r=1,2,...,m. Zero weights are permitted and
               the corresponding points are ignored, except when
               determining x   , x   , y    and y    (see Section 8.4). For
                            min   max   min      max
               advice on the choice of weights, see Section 2.1.2 of the
               Chapter Introduction. Constraint: the number of data points
               with non-zero weight must be at least 16.

           7:  S -- DOUBLE PRECISION                                  Input
               On entry: the smoothing factor, S.

               For advice on the choice of S, see Section 3 and Section 8.2
               . Constraint: S > 0.0.

           8:  NXEST -- INTEGER                                       Input


           9:  NYEST -- INTEGER                                       Input
               On entry: an upper bound for the number of knots n  and n
                                                                 x      y
               required in the x- and y-directions respectively.
                                                                 ___
               In most practical situations, NXEST = NYEST = 4+\/m/2 is
               sufficient. See also Section 8.3. Constraint: NXEST >= 8 and
               NYEST >= 8.

          10:  NX -- INTEGER                                   Input/Output
               On entry: if the warm start option is used, the value of NX
               must be left unchanged from the previous call. On exit: the
               total number of knots, n , of the computed spline with
                                       x
               respect to the x variable.

          11:  LAMDA(NXEST) -- DOUBLE PRECISION array          Input/Output
               On entry: if the warm start option is used, the values LAMDA
               (1), LAMDA(2),...,LAMDA(NX) must be left unchanged from the
               previous call. On exit: LAMDA contains the complete set of
               knots (lambda)  associated with the x variable, i.e., the
                             i
               interior knots LAMDA(5), LAMDA(6),...,LAMDA(NX-4) as well as
               the additional knots LAMDA(1) = LAMDA(2) = LAMDA(3) = LAMDA
               (4) = x    and LAMDA(NX-3) = LAMDA(NX-2) = LAMDA(NX-1) =
                      min
               LAMDA(NX) = x    needed for the B-spline representation
                            max
               (where x    and x    are as described in Section 3).
                       min      max

          12:  NY -- INTEGER                                   Input/Output
               On entry: if the warm start option is used, the value of NY
               must be left unchanged from the previous call. On exit: the
               total number of knots, n , of the computed spline with
                                       y
               respect to the y variable.

          13:  MU(NYEST) -- DOUBLE PRECISION array             Input/Output
               On entry: if the warm start option is used, the values MU(1)
               MU(2),...,MU(NY) must be left unchanged from the previous
               call. On exit: MU contains the complete set of knots (mu)
                                                                        i
               associated with the y variable, i.e., the interior knots MU
               (5), MU(6),...,MU(NY-4) as well as the additional knots MU
               (1) = MU(2) = MU(3) = MU(4) = y    and MU(NY-3) = MU(NY-2) =
                                              min
               MU(NY-1) = MU(NY) = y    needed for the B-spline
                                    max
               representation (where y    and y    are as described in
                                      min      max
               Section 3).

          14:  C((NXEST-4)*(NYEST-4)) -- DOUBLE PRECISION array      Output
               On exit: the coefficients of the spline approximation. C(
               (n -4)*(i-1)+j) is the coefficient c   defined in Section 3.
                 y                                 ij

          15:  FP -- DOUBLE PRECISION                                Output
               On exit: the weighted sum of squared residuals, (theta), of
               the computed spline approximation. FP should equal S within
               a relative tolerance of 0.001 unless NX = NY = 8, when the
               spline has no interior knots and so is simply a bicubic
               polynomial. For knots to be inserted, S must be set to a
               value below the value of FP produced in this case.

          16:  RANK -- INTEGER                                       Output
               On exit: RANK gives the rank of the system of equations used
               to compute the final spline (as determined by a suitable
               machine-dependent threshold). When RANK = (NX-4)*(NY-4), the
               solution is unique; otherwise the system is rank-deficient
               and the minimum-norm solution is computed. The latter case
               may be caused by too small a value of S.

          17:  WRK(LWRK) -- DOUBLE PRECISION array                Workspace
               On entry: if the warm start option is used, the value of WRK
               (1) must be left unchanged from the previous call.

               This array is used as workspace.

          18:  LWRK -- INTEGER                                        Input
               On entry:
               the dimension of the array WRK as declared in the
               (sub)program from which E02DDF is called.
               Constraint: LWRK >= (7*u*v+25*w)*(w+1)+2*(u+v+4*M)+23*w+56,

               where

               u=NXEST-4, v=NYEST-4, and w=max(u,v).

               For some problems, the routine may need to compute the
               minimal least-squares solution of a rank-deficient system of
               linear equations (see Section 3). The amount of workspace
               required to solve such problems will be larger than
               specified by the value given above, which must be increased
               by an amount, LWRK2 say. An upper bound for LWRK2 is given
               by 4*u*v*w+2*u*v+4*w, where u, v and w are as above.
               However, if there are enough data points, scattered
               uniformly over the approximation domain, and if the
               smoothing factor S is not too small, there is a good chance
               that this extra workspace is not needed. A lot of memory
               might therefore be saved by assuming LWRK2 = 0.

          19:  IWRK(LIWRK) -- INTEGER array                       Workspace


          20:  LIWRK -- INTEGER                                       Input
               On entry:
               the dimension of the array IWRK as declared in the
               (sub)program from which E02DDF is called.
               Constraint: LIWRK>=M+2*(NXEST-7)*(NYEST-7).

          21:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          If on entry IFAIL = 0 or -1, explanatory error messages are
          output on the current error message unit (as defined by X04AAF).

          IFAIL= 1
               On entry START /= 'C' or 'W',

               or       the number of data points with non-zero weight <
                        16,

               or       S <= 0.0,

               or       NXEST < 8,

               or       NYEST < 8,

               or       LWRK < (7*u*v+25*w)*(w+1)+2*(u+v+4*M)+23*w+56,
                        where u = NXEST - 4, v = NYEST - 4 and w=max(u,v),

               or       LIWRK <M+2*(NXEST-7)*(NYEST-7).

          IFAIL= 2
               On entry either all the X(r), for r = 1,2,...,M, are equal,
               or all the Y(r), for r = 1,2,...,M, are equal.

          IFAIL= 3
               The number of knots required is greater than allowed by
               NXEST and NYEST. Try increasing NXEST and/or NYEST and, if
               necessary, supplying larger arrays for the parameters LAMDA,
               MU, C, WRK and IWRK. However, if NXEST and NYEST are already
                                               

               large, say NXEST, NYEST > 4 + \/M/2, then this error exit
               may indicate that S is too small.

          IFAIL= 4
               No more knots can be added because the number of B-spline
               coefficients (NX-4)*(NY-4) already exceeds the number of
               data points M. This error exit may occur if either of S or M
               is too small.

          IFAIL= 5
               No more knots can be added because the additional knot would
               (quasi) coincide with an old one. This error exit may occur
               if too large a weight has been given to an inaccurate data
               point, or if S is too small.

          IFAIL= 6
               The iterative process used to compute the coefficients of
               the approximating spline has failed to converge. This error
               exit may occur if S has been set very small. If the error
               persists with increased S, consult NAG.

          IFAIL= 7
               LWRK is too small; the routine needs to compute the minimal
               least-squares solution of a rank-deficient system of linear
               equations, but there is not enough workspace. There is no
               approximation returned but, having saved the information
               contained in NX, LAMDA, NY, MU and WRK, and having adjusted
               the value of LWRK and the dimension of array WRK
               accordingly, the user can continue at the point the program
               was left by calling E02DDF with START = 'W'. Note that the
               requested value for LWRK is only large enough for the
               current phase of the algorithm. If the routine is restarted
               with LWRK set to the minimum value requested, a larger
               request may be made at a later stage of the computation. See
               Section 5 for the upper bound on LWRK. On soft failure, the
               minimum requested value for LWRK is returned in IWRK(1) and
               the safe value for LWRK is returned in IWRK(2).

          If IFAIL = 3,4,5 or 6, a spline approximation is returned, but it
          fails to satisfy the fitting criterion (see (2) and (3) in
          Section 3 -- perhaps only by a small amount, however.

          7. Accuracy

          On successful exit, the approximation returned is such that its
          weighted sum of squared residuals FP is equal to the smoothing
          factor S, up to a specified relative tolerance of 0.001 - except
          that if n =8 and n =8, FP may be significantly less than S: in
                   x        y
          this case the computed spline is simply the least-squares bicubic
          polynomial approximation of degree 3, i.e., a spline with no
          interior knots.

          8. Further Comments

          8.1. Timing

          The time taken for a call of E02DDF depends on the complexity of
          the shape of the data, the value of the smoothing factor S, and
          the number of data points. If E02DDF is to be called for
          different values of S, much time can be saved by setting START =
          It should be noted that choosing S very small considerably
          increases computation time.

          8.2. Choice of S

          If the weights have been correctly chosen (see Section 2.1.2 of
          the Chapter Introduction), the standard deviation of w f  would
                                                                r r
          be the same for all r, equal to (sigma), say. In this case,
                                                              2      
          choosing the smoothing factor S in the range (sigma) (m+-\/2m),
          as suggested by Reinsch [6], is likely to give a good start in
          the search for a satisfactory value. Otherwise, experimenting
          with different values of S will be required from the start.

          In that case, in view of computation time and memory
          requirements, it is recommended to start with a very large value
          for S and so determine the least-squares bicubic polynomial; the
          value returned for FP, call it FP , gives an upper bound for S.
                                           0
          Then progressively decrease the value of S to obtain closer fits
          - say by a factor of 10 in the beginning, i.e., S=FP /10,
                                                              0
          S=FP /100, and so on, and more carefully as the approximation
              0
          shows more details.

          To choose S very small is strongly discouraged. This considerably
          increases computation time and memory requirements. It may also
          cause rank-deficiency (as indicated by the parameter RANK) and
          endanger numerical stability.

          The number of knots of the spline returned, and their location,
          generally depend on the value of S and on the behaviour of the
          function underlying the data. However, if E02DDF is called with
          START = 'W', the knots returned may also depend on the smoothing
          factors of the previous calls. Therefore if, after a number of
          trials with different values of S and START = 'W', a fit can
          finally be accepted as satisfactory, it may be worthwhile to call
          E02DDF once more with the selected value for S but now using
          START = 'C'. Often, E02DDF then returns an approximation with the
          same quality of fit but with fewer knots, which is therefore
          better if data reduction is also important.

          8.3. Choice of NXEST and NYEST

          The number of knots may also depend on the upper bounds NXEST and
          NYEST. Indeed, if at a certain stage in E02DDF the number of
          knots in one direction (say n ) has reached the value of its
                                       x
          upper bound (NXEST), then from that moment on all subsequent
          knots are added in the other (y) direction. This may indicate
          that the value of NXEST is too small. On the other hand, it gives
          the user the option of limiting the number of knots the routine
          locates in any direction. For example, by setting NXEST = 8 (the
          lowest allowable value for NXEST), the user can indicate that he
          wants an approximation which is a simple cubic polynomial in the
          variable x.

          8.4. Restriction of the approximation domain

          The fit obtained is not defined outside the rectangle
          [(lambda) ,(lambda)    ]*[(mu) ,(mu)    ]. The reason for taking
                   4         n -3       4     n -3
                              x                y
          the extreme data values of x and y for these four knots is that,
          as is usual in data fitting, the fit cannot be expected to give
          satisfactory values outside the data region. If, nevertheless,
          the user requires values over a larger rectangle, this can be
          achieved by augmenting the data with two artificial data points
          (a,c,0) and (b,d,0) with zero weight, where [a,b]*[c,d] denotes
          the enlarged rectangle.

          8.5. Outline of method used

          First suitable knot sets are built up in stages (starting with no
          interior knots in the case of a cold start but with the knot set
          found in a previous call if a warm start is chosen). At each
          stage, a bicubic spline is fitted to the data by least-squares
          and (theta), the sum of squares of residuals, is computed. If
          (theta)>S, a new knot is added to one knot set or the other so as
          to reduce (theta) at the next stage. The new knot is located in
          an interval where the fit is particularly poor. Sooner or later,
          we find that (theta)<=S and at that point the knot sets are
          accepted. The routine then goes on to compute a spline which has
          these knot sets and which satisfies the full fitting criterion
          specified by (2) and (3). The theoretical solution has (theta)=S.
          The routine computes the spline by an iterative scheme which is
          ended when (theta)=S within a relative tolerance of 0.001. The
          main part of each iteration consists of a linear least-squares
          computation of special form, done in a similarly stable and
          efficient manner as in E02DAF. As there also, the minimal least-
          squares solution is computed wherever the linear system is found
          to be rank-deficient.

          An exception occurs when the routine finds at the start that,
          even with no interior knots (N = 8), the least-squares spline
          already has its sum of squares of residuals <=S. In this case,
          since this spline (which is simply a bicubic polynomial) also has
          an optimal value for the smoothness measure (eta), namely zero,
          it is returned at once as the (trivial) solution. It will usually
          mean that S has been chosen too large.

          For further details of the algorithm and its use see Dierckx [2].

          8.6. Evaluation of computed spline

          The values of the computed spline at the points (TX(r),TY(r)),
          for r = 1,2,...,N, may be obtained in the double precision array
          FF, of length at least N, by the following code:


                IFAIL = 0
                CALL E02DEF(N,NX,NY,TX,TY,LAMDA,MU,C,FF,WRK,IWRK,IFAIL)


          where NX, NY, LAMDA, MU and C are the output parameters of E02DDF
          , WRK is a double precision workspace array of length at least
          NY-4, and IWRK is an integer workspace array of length at least
          NY-4.

          To evaluate the computed spline on a KX by KY rectangular grid of
          points in the x-y plane, which is defined by the x co-ordinates
          stored in TX(q), for q=1,2,...,KX, and the y co-ordinates stored
          in TY(r), for r=1,2,...,KY, returning the results in the double
          precision array FG which is of length at least KX*KY, the
          following call may be used:


                IFAIL = 0
                CALL E02DFF(KX,KY,NX,NY,TX,TY,LAMDA,MU,C,FG,WRK,LWRK,
               *            IWRK,LIWRK,IFAIL)


          where NX, NY, LAMDA, MU and C are the output parameters of E02DDF
          , WRK is a double precision workspace array of length at least
          LWRK = min(NWRK1,NWRK2), NWRK1 = KX*4+NX, NWRK2 = KY*4+NY, and
          IWRK is an integer workspace array of length at least LIWRK = KY
          + NY - 4 if NWRK1 >= NWRK2, or KX + NX - 4 otherwise. The result
          of the spline evaluated at grid point (q,r) is returned in
          element (KY*(q-1)+r) of the array FG.

          9. Example

          This example program reads in a value of M, followed by a set of
          M data points (x ,y ,f ) and their weights w . It then calls
                          r  r  r                     r
          E02DDF to compute a bicubic spline approximation for one
          specified value of S, and prints the values of the computed knots
          and B-spline coefficients. Finally it evaluates the spline at a
          small sample of points on a rectangular grid.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02DEF
                  E02DEF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02DEF calculates values of a bicubic spline from its B-spline
          representation.

          2. Specification

                 SUBROUTINE E02DEF (M, PX, PY, X, Y, LAMDA, MU, C, FF, WRK,
                1                   IWRK, IFAIL)
                 INTEGER          M, PX, PY, IWRK(PY-4), IFAIL
                 DOUBLE PRECISION X(M), Y(M), LAMDA(PX), MU(PY), C((PX-4)*
                1                 (PY-4)), FF(M), WRK(PY-4)

          3. Description

          This routine calculates values of the bicubic spline s(x,y) at
          prescribed points (x ,y ), for r=1,2,...,m, from its augmented
                              r  r
          knot sets {(lambda)} and {(mu)} and from the coefficients c  ,
                                                                     ij
          for i=1,2,...,PX-4; j=1,2,...,PY-4, in its B-spline
          representation

                                      --
                              s(x,y)= > c  M (x)N (y).
                                      -- ij i    j
                                      ij

          Here M (x) and N (y) denote normalised cubic B-splines, the
                i         j
          former defined on the knots (lambda)  to (lambda)    and the
                                              i            i+4
          latter on the knots (mu)  to (mu)   .
                                  j        j+4

          This routine may be used to calculate values of a bicubic spline
          given in the form produced by E01DAF, E02DAF, E02DCF and E02DDF.
          It is derived from the routine B2VRE in Anthony et al [1].

          4. References

          [1]   Anthony G T, Cox M G and Hayes J G (1982) DASL - Data
                Approximation Subroutine Library. National Physical
                Laboratory.

          [2]   Cox M G (1978) The Numerical Evaluation of a Spline from its
                B-spline Representation. J. Inst. Math. Appl. 21 135--143.

          5. Parameters

           1:  M -- INTEGER                                           Input
               On entry: m, the number of points at which values of the
               spline are required. Constraint: M >= 1.

           2:  PX -- INTEGER                                          Input

           3:  PY -- INTEGER                                          Input
               On entry: PX and PY must specify the total number of knots
               associated with the variables x and y respectively. They are
               such that PX-8 and PY-8 are the corresponding numbers of
               interior knots. Constraint: PX >= 8 and PY >= 8.

           4:  X(M) -- DOUBLE PRECISION array                         Input

           5:  Y(M) -- DOUBLE PRECISION array                         Input
               On entry: X and Y must contain x  and y , for r=1,2,...,m,
                                               r      r
               respectively. These are the co-ordinates of the points at
               which values of the spline are required. The order of the
               points is immaterial. Constraint: X and Y must satisfy

               LAMDA(4) <= X(r) <= LAMDA(PX-3)

               and

               MU(4) <= Y(r) <= MU(PY-3), for r=1,2,...,m.

               The spline representation is not valid outside these
               intervals.

           6:  LAMDA(PX) -- DOUBLE PRECISION array                    Input

           7:  MU(PY) -- DOUBLE PRECISION array                       Input
               On entry: LAMDA and MU must contain the complete sets of
               knots {(lambda)} and {(mu)} associated with the x and y
               variables respectively. Constraint: the knots in each set
               must be in non-decreasing order, with LAMDA(PX-3) > LAMDA(4)
               and MU(PY-3) > MU(4).

           8:  C((PX-4)*(PY-4)) -- DOUBLE PRECISION array             Input
               On entry: C((PY-4)*(i-1)+j) must contain the coefficient
               c   described in Section 3, for i=1,2,...,PX-4;
                ij
               j=1,2,...,PY-4.

           9:  FF(M) -- DOUBLE PRECISION array                       Output
               On exit: FF(r) contains the value of the spline at the
               point (x ,y ), for r=1,2,...,m.
                       r  r

          10:  WRK(PY-4) -- DOUBLE PRECISION array                Workspace

          11:  IWRK(PY-4) -- INTEGER array                        Workspace

          12:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          If on entry IFAIL = 0 or -1, explanatory error messages are
          output on the current error message unit (as defined by X04AAF).

          IFAIL= 1
               On entry M < 1,

               or       PY < 8,

               or       PX < 8.

          IFAIL= 2
               On entry the knots in array LAMDA, or those in array MU, are
               not in non-decreasing order, or LAMDA(PX-3) <= LAMDA(4), or
               MU(PY-3) <= MU(4).

          IFAIL= 3
               On entry at least one of the prescribed points (x ,y ) lies
                                                                r  r
               outside the rectangle defined by LAMDA(4), LAMDA(PX-3) and
               MU(4), MU(PY-3).

          7. Accuracy

          The method used to evaluate the B-splines is numerically stable,
          in the sense that each computed value of s(x ,y ) can be regarded
                                                      r  r
          as the value that would have been obtained in exact arithmetic
          from slightly perturbed B-spline coefficients. See Cox [2] for
          details.

          8. Further Comments

          Computation time is approximately proportional to the number of
          points, m, at which the evaluation is required.

          9. Example

          This program reads in knot sets LAMDA(1),..., LAMDA(PX) and MU(1)
          ,..., MU(PY), and a set of bicubic spline coefficients c  .
                                                                  ij
          Following these are a value for m and the co-ordinates (x ,y ),
                                                                   r  r
          for r=1,2,...,m, at which the spline is to be evaluated.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02DFF
                  E02DFF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02DFF calculates values of a bicubic spline from its B-spline
          representation. The spline is evaluated at all points on a
          rectangular grid.

          2. Specification

                 SUBROUTINE E02DFF (MX, MY, PX, PY, X, Y, LAMDA, MU, C, FF,
                1                   WRK, LWRK, IWRK, LIWRK, IFAIL)
                 INTEGER          MX, MY, PX, PY, LWRK, IWRK(LIWRK), LIWRK,
                1                 IFAIL
                 DOUBLE PRECISION X(MX), Y(MY), LAMDA(PX), MU(PY), C((PX-4)*
                1                 (PY-4)), FF(MX*MY), WRK(LWRK)

          3. Description

          This routine calculates values of the bicubic spline s(x,y) on a
          rectangular grid of points in the x-y plane, from its augmented
          knot sets {(lambda)} and {(mu)} and from the coefficients c  ,
                                                                     ij
          for i=1,2,...,PX-4; j=1,2,...,PY-4, in its B-spline
          representation

                                      --
                              s(x,y)= > c  M (x)N (y).
                                      -- ij i    j
                                      ij

          Here M (x) and N (y) denote normalised cubic B-splines, the
                i         j
          former defined on the knots (lambda)  to (lambda)    and the
                                              i            i+4
          latter on the knots (mu)  to (mu)   .
                                  j        j+4

          The points in the grid are defined by co-ordinates x , for
                                                              q
          q=1,2,...,m , along the x axis, and co-ordinates y , for
                     x                                      r
          r=1,2,...,m  along the y axis.
                     y

          This routine may be used to calculate values of a bicubic spline
          given in the form produced by E01DAF, E02DAF, E02DCF and E02DDF.
          It is derived from the routine B2VRE in Anthony et al [1].

          4. References

          [1]   Anthony G T, Cox M G and Hayes J G (1982) DASL - Data
                Approximation Subroutine Library. National Physical
                Laboratory.

          [2]   Cox M G (1978) The Numerical Evaluation of a Spline from its
                B-spline Representation. J. Inst. Math. Appl. 21 135--143.

          5. Parameters

           1:  MX -- INTEGER                                          Input

           2:  MY -- INTEGER                                          Input
               On entry: MX and MY must specify m  and m  respectively,
                                                 x      y
               the number of points along the x and y axis that define the
               rectangular grid. Constraint: MX >= 1 and MY >= 1.

           3:  PX -- INTEGER                                          Input

           4:  PY -- INTEGER                                          Input
               On entry: PX and PY must specify the total number of knots
               associated with the variables x and y respectively. They are
               such that PX-8 and PY-8 are the corresponding numbers of
               interior knots. Constraint: PX >= 8 and PY >= 8.

           5:  X(MX) -- DOUBLE PRECISION array                        Input

           6:  Y(MY) -- DOUBLE PRECISION array                        Input
               On entry: X and Y must contain x , for q=1,2,...,m , and y ,
                                               q                 x       r
               for r=1,2,...,m , respectively. These are the x and y co-
                              y
               ordinates that define the rectangular grid of points at
               which values of the spline are required. Constraint: X and Y
               must satisfy

               LAMDA(4) <= X(q) < X(q+1) <= LAMDA(PX-3), for q=1,2,...,m -1
                                                                        x
               and

               MU(4) <= Y(r) < Y(r+1) <= MU(PY-3), for r=1,2,...,m -1.
                                                                  y

               The spline representation is not valid outside these
               intervals.

           7:  LAMDA(PX) -- DOUBLE PRECISION array                    Input

           8:  MU(PY) -- DOUBLE PRECISION array                       Input
               On entry: LAMDA and MU must contain the complete sets of
               knots {(lambda)} and {(mu)} associated with the x and y
               variables respectively. Constraint: the knots in each set
               must be in non-decreasing order, with LAMDA(PX-3) > LAMDA(4)
               and MU(PY-3) > MU(4).

           9:  C((PX-4)*(PY-4)) -- DOUBLE PRECISION array             Input
               On entry: C((PY-4)*(i-1)+j) must contain the coefficient
               c   described in Section 3, for i=1,2,...,PX-4;
                ij
               j=1,2,...,PY-4.

          10:  FF(MX*MY) -- DOUBLE PRECISION array                   Output
               On exit: FF(MY*(q-1)+r) contains the value of the spline at
               the point (x ,y ), for q=1,2,...,m ; r=1,2,...,m .
                           q  r                  x             y

          11:  WRK(LWRK) -- DOUBLE PRECISION array                Workspace

          12:  LWRK -- INTEGER                                        Input
               On entry:
               the dimension of the array WRK as declared in the
               (sub)program from which E02DFF is called.
               Constraint: LWRK >= min(NWRK1,NWRK2), where NWRK1=4*MX+PX,
               NWRK2=4*MY+PY.

          13:  IWRK(LIWRK) -- INTEGER array                       Workspace

          14:  LIWRK -- INTEGER                                       Input
               On entry:
               the dimension of the array IWRK as declared in the
               (sub)program from which E02DFF is called.
               Constraint: LIWRK >= MY + PY - 4 if NWRK1 > NWRK2, or MX +
               PX - 4 otherwise, where NWRK1 and NWRK2 are as defined in
               the description of argument LWRK.

          15:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          If on entry IFAIL = 0 or -1, explanatory error messages are
          output on the current error message unit (as defined by X04AAF).

          IFAIL= 1
               On entry MX < 1,

               or       MY < 1,

               or       PY < 8,

               or       PX < 8.

          IFAIL= 2
               On entry LWRK is too small,

               or       LIWRK is too small.

          IFAIL= 3
               On entry the knots in array LAMDA, or those in array MU, are
               not in non-decreasing order, or LAMDA(PX-3) <= LAMDA(4), or
               MU(PY-3) <= MU(4).

          IFAIL= 4
               On entry the restriction LAMDA(4) <= X(1) <... < X(MX) <=
               LAMDA(PX-3), or the restriction MU(4) <= Y(1) <... < Y(MY)
               <= MU(PY-3), is violated.

          7. Accuracy

          The method used to evaluate the B-splines is numerically stable,
          in the sense that each computed value of s(x ,y ) can be regarded
                                                      r  r
          as the value that would have been obtained in exact arithmetic
          from slightly perturbed B-spline coefficients. See Cox [2] for
          details.

          8. Further Comments

          Computation time is approximately proportional to m m +4(m +m ).
                                                             x y    x  y

          9. Example

          This program reads in knot sets LAMDA(1),..., LAMDA(PX) and MU(1)
          ,..., MU(PY), and a set of bicubic spline coefficients c  .
                                                                  ij
          Following these are values for m  and the x co-ordinates x , for
                                          x                         q
          q=1,2,...,m , and values for m  and the y co-ordinates y , for
                     x                  y                         r
          r=1,2,...,m , defining the grid of points on which the spline is
                     y
          to be evaluated.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02GAF
                  E02GAF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02GAF calculates an l  solution to an over-determined system of
                                1
          linear equations.

          2. Specification

                 SUBROUTINE E02GAF (M, A, LA, B, NPLUS2, TOLER, X, RESID,
                1                   IRANK, ITER, IWORK, IFAIL)
                 INTEGER          M, LA, NPLUS2, IRANK, ITER, IWORK(M),
                1                 IFAIL
                 DOUBLE PRECISION A(LA,NPLUS2), B(M), TOLER, X(NPLUS2),
                1                 RESID

          3. Description

          Given a matrix A with m rows and n columns (m>=n) and a vector b
          with m elements, the routine calculates an l  solution to the
                                                      1
          over-determined system of equations

                                        Ax=b.

          That is to say, it calculates a vector x, with n elements, which
          minimizes the l -norm (the sum of the absolute values) of the
                         1
          residuals

                                         m
                                         --
                                   r(x)= >  |r |,
                                         --   i
                                         i=1

          where the residuals r  are given by
                               i

                                  n
                                  --
                           r =b - >  a  x ,   i=1,2,...,m.
                            i  i  --  ij j
                                  j=1

          Here a   is the element in row i and column j of A, b  is the ith
                ij                                             i
          element of b and x  the jth element of x. The matrix A need not
                            j
          be of full rank.

          Typically in applications to data fitting, data consisting of m
          points with co-ordinates (t ,y ) are to be approximated in the l
                                     i  i                                 1
          -norm by a linear combination of known functions (phi) (t),
                                                                j

             (alpha) (phi) (t)+(alpha) (phi) (t)+...+(alpha) (phi) (t).
                    1     1           2     2               n     n

          This is equivalent to fitting an l  solution to the over-
                                            1
          determined system of equations

                       n
                       --
                       >  (phi) (t )(alpha) =y ,   i=1,2,...,m.
                       --      j  i        j  i
                       j=1

          Thus if, for each value of i and j, the element a   of the matrix
                                                           ij
          A in the previous paragraph is set equal to the value of
          (phi) (t ) and b  is set equal to y , the solution vector x will
               j  i       i                  i
          contain the required values of the (alpha) . Note that the
                                                    j
          independent variable t above can, instead, be a vector of several
          independent variables (this includes the case where each (phi)
                                                                        i
          is a function of a different variable, or set of variables).

          The algorithm is a modification of the simplex method of linear
          programming applied to the primal formulation of the l  problem
                                                                1
          (see Barrodale and Roberts [1] and [2]). The modification allows
          several neighbouring simplex vertices to be passed through in a
          single iteration, providing a substantial improvement in
          efficiency.

          4. References

          [1]   Barrodale I and Roberts F D K (1973) An Improved Algorithm
                for Discrete \\ll  Linear Approximation. SIAM J. Numer.
                                 1
                Anal. 10 839--848.

          [2]   Barrodale I and Roberts F D K (1974) Solution of an
                Overdetermined System of Equations in the \\ll -norm. Comm.
                                                              1
                ACM. 17, 6 319--320.

          5. Parameters

           1:  M -- INTEGER                                           Input
               On entry: the number of equations, m (the number of rows of
               the matrix A). Constraint: M >= n >= 1.

           2:  A(LA,NPLUS2) -- DOUBLE PRECISION array          Input/Output
               On entry: A(i,j) must contain a  , the element in the ith
                                              ij
               row and jth column of the matrix A, for i=1,2,...,m and
               j=1,2,...,n. The remaining elements need not be set. On
               exit: A contains the last simplex tableau generated by the
               simplex method.

           3:  LA -- INTEGER                                          Input
               On entry:
               the first dimension of the array A as declared in the
               (sub)program from which E02GAF is called.
               Constraint: LA >= M + 2.

           4:  B(M) -- DOUBLE PRECISION array                  Input/Output
               On entry: b , the ith element of the vector b, for
                          i
               i=1,2,...,m. On exit: the ith residual r  corresponding to
                                                       i
               the solution vector x, for i=1,2,...,m.

           5:  NPLUS2 -- INTEGER                                      Input
               On entry: n+2, where n is the number of unknowns (the
               number of columns of the matrix A). Constraint: 3 <= NPLUS2
               <= M + 2.

           6:  TOLER -- DOUBLE PRECISION                              Input
               On entry: a non-negative value. In general TOLER specifies
               a threshold below which numbers are regarded as zero. The
                                                       2/3
               recommended threshold value is (epsilon)    where (epsilon)
               is the machine precision. The recommended value can be
               computed within the routine by setting TOLER to zero. If
               premature termination occurs a larger value for TOLER may
               result in a valid solution. Suggested value: 0.0.

           7:  X(NPLUS2) -- DOUBLE PRECISION array                   Output
               On exit: X(j) contains the jth element of the solution
               vector x, for j=1,2,...,n. The elements X(n+1) and X(n+2)
               are unused.

           8:  RESID -- DOUBLE PRECISION                             Output
               On exit: the sum of the absolute values of the residuals
               for the solution vector x.

           9:  IRANK -- INTEGER                                      Output
               On exit: the computed rank of the matrix A.

          10:  ITER -- INTEGER                                       Output
               On exit: the number of iterations taken by the simplex
               method.

          11:  IWORK(M) -- INTEGER array                          Workspace

          12:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          IFAIL= 1
               An optimal solution has been obtained but this may not be
               unique.

          IFAIL= 2
               The calculations have terminated prematurely due to rounding
               errors. Experiment with larger values of TOLER or try
               scaling the columns of the matrix (see Section 8).

          IFAIL= 3
               On entry NPLUS2 < 3,

               or       NPLUS2 > M + 2,

               or       LA < M + 2.

          7. Accuracy

          Experience suggests that the computational accuracy of the
          solution x is comparable with the accuracy that could be obtained
          by applying Gaussian elimination with partial pivoting to the n
          equations satisfied by this algorithm (i.e., those equations with
          zero residuals). The accuracy therefore varies with the
          conditioning of the problem, but has been found generally very
          satisfactory in practice.

          8. Further Comments

          The effects of m and n on the time and on the number of
          iterations in the Simplex Method vary from problem to problem,
          but typically the number of iterations is a small multiple of n
          and the total time taken by the routine is approximately
                            2
          proportional to mn .

          It is recommended that, before the routine is entered, the
          columns of the matrix A are scaled so that the largest element in
          each column is of the order of unity. This should improve the
          conditioning of the matrix, and also enable the parameter TOLER
          to perform its correct function. The solution x obtained will
          then, of course, relate to the scaled form of the matrix. Thus if
          the scaling is such that, for each j=1,2,...,n, the elements of
          the jth column are multiplied by the constant k , the element x
                                                         j               j
          of the solution vector x must be multiplied by k  if it is
                                                          j
          desired to recover the solution corresponding to the original
          matrix A.

          9. Example

          Suppose we wish to approximate a set of data by a curve of the
          form

                   t   -t
               y=Ke +Le  +M

          where K, L and M are unknown. Given values y  at 5 points t  we
                                                      i              i
          may form the over-determined set of equations for K, L and M

                            x    -x
                             i     i
                           e  K+e   L+M=y ,  i=1,2,...,5.
                                         i

          E02GAF is used to solve these in the l  sense.
                                                1

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

          E02 -- Curve and Surface Fitting                           E02ZAF
                  E02ZAF -- NAG Foundation Library Routine Document

          Note: Before using this routine, please read the Users' Note for
          your implementation to check implementation-dependent details.
          The symbol (*) after a NAG routine name denotes a routine that is
          not included in the Foundation Library.

          1. Purpose

          E02ZAF sorts two-dimensional data into rectangular panels.

          2. Specification

                 SUBROUTINE E02ZAF (PX, PY, LAMDA, MU, M, X, Y, POINT,
                1                   NPOINT, ADRES, NADRES, IFAIL)
                 INTEGER          PX, PY, M, POINT(NPOINT), NPOINT, ADRES
                1                 (NADRES), NADRES, IFAIL
                 DOUBLE PRECISION LAMDA(PX), MU(PY), X(M), Y(M)

          3. Description

          A set of m data points with rectangular Cartesian co-ordinates
          x ,y  are sorted into panels defined by lines parallel to the y
           r  r
          and x axes. The intercepts of these lines on the x and y axes are
          given in LAMDA(i), for i=5,6,...,PX-4 and MU(j), for
          j=5,6,...,PY-4, respectively. The subroutine orders the data so
          that all points in a panel occur before data in succeeding
          panels, where the panels are numbered from bottom to top and then
          left to right, with the usual arrangement of axes, as shown in
          the diagram. Within a panel the points maintain their original
          order.

                   Please see figure in printed Reference Manual

          A data point lying exactly on one or more panel sides is taken to
          be in the highest-numbered panel adjacent to the point. The
          subroutine does not physically rearrange the data, but provides
          the array POINT which contains a linked list for each panel,
          pointing to the data in that panel. The total number of panels is
          (PX-7)*(PY-7).

          4. References

          None.

          5. Parameters

           1:  PX -- INTEGER                                          Input

           2:  PY -- INTEGER                                          Input

               On entry: PX and PY must specify eight more than the number
               of intercepts on the x axis and y axis, respectively.
               Constraint: PX >= 8 and PY >= 8.

           3:  LAMDA(PX) -- DOUBLE PRECISION array                    Input
               On entry: LAMDA(5) to LAMDA(PX-4) must contain, in non-
               decreasing order, the intercepts on the x axis of the sides
               of the panels parallel to the y axis.

           4:  MU(PY) -- DOUBLE PRECISION array                       Input
               On entry: MU(5) to MU(PY-4) must contain, in non-decreasing
               order, the intercepts on the y axis of the sides of the
               panels parallel to the x axis.

           5:  M -- INTEGER                                           Input
               On entry: the number m of data points.

           6:  X(M) -- DOUBLE PRECISION array                         Input

           7:  Y(M) -- DOUBLE PRECISION array                         Input
               On entry: the co-ordinates of the rth data point (x ,y ),
                                                                  r  r
               for r=1,2,...,m.

           8:  POINT(NPOINT) -- INTEGER array                        Output
               On exit: for i = 1,2,...,NADRES, POINT(m+i) = I1 is the
               index of the first point in panel i, POINT(I1) = I2 is the
               index of the second point in panel i and so on.

               POINT(IN) = 0 indicates that X(IN),Y(IN) was the last point
               in the panel.

               The co-ordinates of points in panel i can be accessed in
               turn by means of the following instructions:
                  IN = M + I
               10 IN = POINT(IN)
                  IF (IN.EQ. 0) GOTO 20
                  XI = X(IN)
                  YI = Y(IN)
                  .
                  .
                  .
                  GOTO 10
               20...

           9:  NPOINT -- INTEGER                                      Input
               On entry:
               the dimension of the array POINT as declared in the
               (sub)program from which E02ZAF is called.
               Constraint: NPOINT >= M + (PX-7)*(PY-7).

          10:  ADRES(NADRES) -- INTEGER array                     Workspace

          11:  NADRES -- INTEGER                                      Input
               On entry: the value (PX-7)*(PY-7), the number of panels
               into which the (x,y) plane is divided.

          12:  IFAIL -- INTEGER                                Input/Output
               On entry: IFAIL must be set to 0, -1 or 1. For users not
               familiar with this parameter (described in the Essential
               Introduction) the recommended value is 0.

               On exit: IFAIL = 0 unless the routine detects an error (see
               Section 6).

          6. Error Indicators and Warnings

          Errors detected by the routine:

          If on entry IFAIL = 0 or -1, explanatory error messages are
          output on the current error message unit (as defined by X04AAF).

          IFAIL= 1
               The intercepts in the array LAMDA, or in the array MU, are
               not in non-decreasing order.

          IFAIL= 2
               On entry PX < 8,

               or       PY < 8,

               or       M <= 0,

               or       NADRES /= (PX-7)*(PY-7),

               or       NPOINT < M + (PX-7)*(PY-7).

          7. Accuracy

          Not applicable.

          8. Further Comments

          The time taken by this routine is approximately proportional to
          m*log(NADRES).

          This subroutine was written to sort two dimensional data in the
          manner required by routines E02DAF and E02DBF(*). The first 9
          parameters of E02ZAF are the same as the parameters in E02DAF and
          E02DBF(*) which have the same name.

          9. Example

          This example program reads in data points and the intercepts of
          the panel sides on the x and y axes; it calls E02ZAF to set up
          the index array POINT; and finally it prints the data points in
          panel order.

          The example program is not reproduced here. The source code for
          all example programs is distributed with the NAG Foundation
          Library software and should be available on-line.

