n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - peoplejpeterson/lecture_week10.pdf · ement) we might include...

57
When we write a subprogram to evaluate the polynomial at a point we have to pass into the subprogram the degree of polynomial n (or the number of points n +1); the array containing the points x i , i =1,...,n +1 the array containing the points y i , i =1,...,n +1 the array containing coefficients that we computed the point we want to evaluate it at To calculate the coefficients we needed the first three items. Wouldn’t it be nice if we could group all of these variables and arrays together and give them one name so that we pass one variable instead of several? Fortran allows you do to this by defining what is called a derived type. This is a type of data structure.

Upload: others

Post on 09-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

When we write a subprogram to evaluate the polynomial at a point we have topass into the subprogram

• the degree of polynomial n (or the number of points n + 1);

• the array containing the points xi, i = 1, . . . , n + 1

• the array containing the points yi, i = 1, . . . , n + 1

• the array containing coefficients that we computed

• the point we want to evaluate it at

To calculate the coefficients we needed the first three items.

Wouldn’t it be nice if we could group all of these variables and arrays togetherand give them one name so that we pass one variable instead of several?

Fortran allows you do to this by defining what is called a derived type.

This is a type of data structure.

Page 2: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Derived Data Types and the TYPE Construct

• Allowing the user to define a data structure is a powerful tool. The terminologydata type, data structure, or derived data type are used synonymously.

•We saw that to store elements of all the same type (integer, real, character,etc.) we used an array.

• To store elements of different types (or the same type) which are related insome way, we can use a derived data type for a data structure defined throughthe type construct.

• For a derived data type we want to name the data type (or data structure)and give the attributes (or components) which define an object in the datatype.

• For our Lagrange polynomial data structure we want to specify the numberof points, the arrays for xi, yi and the coefficients. However, we want to startoff with a simpler example to see how derived types work.

Page 3: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Fortran 90 uses the type statement to define a derived data type; this alongwith associated subprograms will form a class.

Syntax for Type Statement

type name

list of components with declaration

end type name

Page 4: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

A sample rectangle data structure which has 4 real variables.

type rectangle

real(prec) :: width

real(prec) :: height

real(prec) :: area

real(prec) :: perimeter

end type rectangle

Page 5: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

•What do we need to define a data structure?

– The name of the data type.

– Decalaration of each attribute or component of the data structure (such aslength or width of rectangle).

• For example, if we define a data structure called element (for a periodic el-ement) we might include its symbol (a character), its atomic number (aninteger), its atomic weight (a real number), etc.

• A useful consequence of using a data structure which has several declareddata types is that instead of passing all the variables through arguments of acalling statement we can simply pass the name of the data structure. Thisreduces errors concerning mismatch of arguments and makes the code morereadable.

Page 6: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Where do we put our data structure definitions prescribed via the type state-ment?

•We view a module as containing all routines for a particular data structure(s).

• Consequently we should define the derived data type at

– the beginning of the module

– after the implicit none statement (because you will be declaring vari-ables)

– before contains

Page 7: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

The Module Revisited

The structure of a module with a data type definition (i.e., a derived type)

module name

implicit none

type statements

contains

subprograms (functions and subroutines) related to defined data structure

end module name

Page 8: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

How does the main program know that an object is a member of a data structure?

• Recall that we include a use module name in the main program to haveaccess to the subprograms in the module. Now it will also inherit the datatype definitions from the module.

• Suppose we have defined a data structure called rectangle with attributeswidth , height, area and perimeter.

• To identify an object as a member of this data type then we must declare itas such, just like we declare a variable as a real, integer, etc.

• The syntax we use is, e.g., type(rectangle) :: rect This definesthe object rect as a member of the data structure rectangle.

•We do not have to declare its attributes because this is done in the type

statement in the module.

•When we pass rect as an argument to a subprogram, then we are reallypassing all four variables width , height, area and perimeter.

Page 9: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

• How can we access one of the attributes of a member of a data structure?

For example, if we pass rect how do we access the width?

– The syntax rect % width says to look at the object rect which hasbeen defined by the type statement as a member of the data structurerectangle and access the attribute width. If we type

print∗, rect%width

then the current value of the width would be printed. Using this notation,the area of a rectangle could be computed as

rect%area = rect%width ∗ rect%length

– Note that we have to use the exact name that we declared as an attributein the type statement. That is, we couldn’t say rect % w because w isnot an attribute of a member of the rectangle data structure. This wouldgenerate a compiler error.

– If we type print *, rect then it will print out the components of thismember of the rectangle data structure in the order which they were defined.

Page 10: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

What subprograms do we need to go with the rectangle data structure?

•We would need a subprogram to determine its area and store in data structure.

•We would need a subprogram to determine its perimeter and store in datastructure.

•What else?

• Typically we also add a constructor. In our case this would be a routine whichpasses in the variables say wid,len and output our data type rect where wehave set rect % width = wid, rect % length = len

Page 11: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Sample module for defining a rectangle class

module class rectangle

use common data

implicit none

type rectangle ! definition of rectangle data structure

real(prec) :: width, height

real(prec) :: area

real(prec) :: perimeter

end type rectangle

contains

Page 12: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

function make rectangle (w, len) result (rect) ! constructor

type (rectangle) :: rect

real :: w, len

rect % width= w

rect % length = len

end function make rectangle

subroutine compute area rectangle ( rect )

type (rectangle) :: rect

rect % area = rect % width * rect % height

end subroutine compute area rectangle

end module class rectangle

We would also add a routine to calculate the perimeter of the rectangle.

Page 13: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

What does the driver routine look like?

use class_rectangle

implicit none

!

type ( rectangle ) :: rect ! define rect as member of data type rectangle

!

real(prec) :: w, h

!

! read in values of width and height of rectangle and then call constructor to set rect

!

print *, "enter two sides of rectangle separated by comma"

read (*, *) w, h

!

rect = make_rectangle ( w, h )

!

! Test routine for computing area of a rectangle

call compute_area_rectangle ( rect)

!

Page 14: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

print *, "area of a rectangle with width", rect % width,"and", &

" height", rect % length,"is ", rect % area

Page 15: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Classwork

1. The first module in file class geometry.f90 contains the derived type def-inition for rectangle along with a constructor function and a subroutine tocalculate area. Add a subprogram to compute the perimeter of the rectangleusing the data structure rectangle.

2. The driver test geometry.f90 contains the commands described on theprevious two slides. Add a call to your routine to calculate the perimeter ofthe rectangle and print out the perimeter.

3. The second module in class geometry.f90 contains a data structure fora circle. Add a function to use as a constructor analogous to the one forrectangle, then add one to calculate the area of the circle with given radiusand store in data structure.

4. Add statements in your driver program to read in the radius of the circle,invoke the constructor and call the subroutine to calculate area; print outarea.

Page 16: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

A Data Structure for the Interpolating Polynomial

For our data type we want to use the following attributes or components

• Number of points

• The data point arrays for (xi, yi)

• The coefficients we calculate

The only difference in this data type and the one we did for rectangles is the factthat we are using arrays. Unfortunately, we can’t declare their size in the type

declaration but rather in the constructor function; in the type declaration wetreat them as we did to dimension with the allocate statement except now weuse pointer instead of allocate.

Page 17: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

type inter_poly

integer :: n_points

real, pointer, dimension (:) :: x

real, pointer, dimension (:) :: y

real,pointer, dimension(:) :: coefficients

end type inter_poly

Now instead of passing the arrays for x, y, the coefficients and the number ofpoints into a subprogram we simply pass in our data structure.

Let’s look at the module. First we define the data structure and the constructor.

Page 18: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

module class_inter_poly

!

use common_data

implicit none

!

type inter_poly

integer :: n_points

real , pointer, dimension (:) :: x,y

real, pointer, dimension(:) :: coefficients

end type inter_poly

!

!*****************************************************

contains

!

!*****************************************************

!*****************************************************

!

Page 19: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

function make_inter_poly ( n ) result ( poly )

!

! Constructor for data structure to set number of points and

! dimension arrays

!

integer :: n

type ( inter_poly ) :: poly

poly % n_points = n

allocate ( poly % x(n), poly % y(n) ) ! dimension x,y arrays

allocate ( poly % coefficients(n) ) ! dimension coefficent array

end function make_lagrange

Now let’s add your routine to evaluate the coefficients.

Page 20: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

subroutine compute_coefficients ( poly )

type ( inter_poly ) :: poly

integer :: n, i, j

real :: den

real :: xi, yi

n = poly % n_points

do i =1, n

xi = poly % x(i)

yi = poly % y(i)

den = one

do j = 1, n

if ( j /= i ) den = den * ( xi - poly % x(j) )

Page 21: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

end do

poly % coefficients ( i ) = yi /den

end do

end subroutine compute_coefficients

Now let’s add the routine to evaluate the polynomial at a point.

!

!*****************************************************

!

function evaluate_polynomial ( x, poly ) result ( pn_at_x)

type ( inter_poly ) :: poly

integer :: i, j ! do loop counters

Page 22: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

integer :: n ! number of points

real :: pn_at_x ! value of polynomial at x

real :: prod

real :: x ! point to evaluate polynomial at

pn_at_x = zero

n = poly % n_points

do i = 1, n

prod = one

do j = 1, n

if ( j /= i ) prod = prod * ( x- poly % x(j) )

end do

pn_at_x = pn_at_x + prod * poly % coefficients(i)

Page 23: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

end do

end function evaluate_polynomial

!*****************************************************

!*****************************************************

end module class_inter_poly

!*****************************************************

Page 24: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

What does our driver program look like?

We want to construct an interpolating polynomial for a function f (x); i.e.,yi = f (xi) and plot for now. Later we will use the interpolating polynomialfor calculating an approximate integral of f (x)

•We have to add a use statement to give access to the module.

•We have to declare data structure, say poly as the derived type inter poly

type(inter poly) :: poly

•We input (or set) the number of points and call the constructor make inter poly

to set the number of points in the data structure and dimension arrays.

•We set up the arrays for (xi, yi)

•We call the routine to calculate the coefficients and store in the data structure.

•We loop over the number of points to evaluate the polynomial at; call thesubroutine evaluate polynomial and write off xi and the value of thepolynomial there for plotting.

Page 25: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Driver for Interpolating Polynomial Module

use class_inter_poly

use common_data

implicit none

type ( inter_poly ) :: poly

integer, parameter :: n_points = 4 ! number of points to interpolate

integer, parameter :: n_points_eval = 101 ! number of points to evaluate polynomial at

real, parameter :: a= zero, b = three ! interval to evaluate polynomial for plotting, etc.

real :: pn

real :: x, delta_x

integer :: i

open (unit=15, file="output_poly.txt" )

Page 26: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

!

!**********************************************************************

! Call constructor to set number of points and dimension arrays

poly = make_inter_poly (n_points )

!

!**********************************************************************

! Set the uniformly spaced (x_i,y_i) points on [a,b] to interpolate

! y_i is found by evaluating f(x_i)

delta_x = (b-a)/ dfloat(n_points - 1)

x = - delta_x

do i = 1, n_points

x = x + delta_x

poly % x(i) = x; poly % y(i) = fx (x )

end do

print *, poly% x

Page 27: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

!

!**********************************************************************

! Call routine to calculate the coefficients and store in data structure

call compute_coefficients (poly)

!

!**********************************************************************

!

!

delta_x = (b-a) / dfloat (n_points_eval - 1 )

x = - delta_x

do i = 1, n_points_eval

x = x + delta_x

pn = evaluate_polynomial ( x, poly)

write ( 15,* ) x, pn, fx(x)

Page 28: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

end do

!

!**********************************************************************

!**********************************************************************

contains

!**********************************************************************

!**********************************************************************

function fx ( x) result (value )

real :: x

real :: value

value = sin ( x * x )

end function fx

Page 29: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Approximating∫ ba f (x)dx

• Now we have a polynomial pn(x) which approximates f (x) so we can approx-imate an integral of f (x) by∫ b

a

f (x) dx ≈∫ b

a

pn(x) dx

• Remember that we don’t actually compute a formula for pn(x); rather we justevaluate it at some points.

• Recall that we used Monte Carlo to approximate the value of an integralby creating a bounding box around the area and then generating a randomnumber in that box and deciding if it is below the curve or above it. Theapproximation to the integral is then the fraction of the bounding box createdby taking the ratio of the number of points in the desired area over the totalnumber of points. This is what you have to implement for your next Project!

Page 30: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Classwork

1. Run the driver routine for the interpolating polynomial and plot f (x) = sin(x2)and the interpolating polynomial. Make sure that the polynomial interpolatesf (x) at the given points.

2. Add statements to the driver to estimate the relative Euclidean norm of theerror, i.e., compute a vector of errors ~E where

Ei = f (zi)− pn(zi)

for the same points zi that you used for plotting. Then compute

‖ ~E‖2‖~f‖2

where ~f is the vector whose components are f (zi). Recall that you alreadyhave a subprogram to calculate the Euclidean norm.

3. In the code we interpolated f (x) at 4 points. Now calculate the relativeEuclidean norm of the error for 4, 8, 16, and 32 uniformly spaced interpolating

Page 31: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

points. Make a table of your results in a file. What do you notice as the pointsincrease?

Page 32: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Summary of Polynomial Interpolation

• The problem we addressed was to find a polynomial which interpolates (i.e.,agrees with or passes through) a given set of points (xi, yi).

• An equivalent problem is approximating a complicated function by determiningan interpolating polynomial.

•We said this polynomial is guaranteed to be unique if the points are distinct.

• One way to find this polynomial is to write it as pn(x) = a0 + a1x+ · · · anxnand then determine the n + 1 linear equations so that pn(xi) = yi, i =1, 2, . . . , n + 1.

• This approach is computationally intensive because we have to solve n + 1linear equations.

•We looked at the Lagrange form of the interpolating polynomial which writesthe nth degree polynomial as a combination of nth degree polynomials Li

Page 33: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

which have the property that Li(xj) = 0 if i 6= j and =1 if i = j. We wroteroutines to determine the coefficients and evaluate the polynomial at a point.

• There is another form of the interpolating polynomial - the Newton form -which has the advantage that we can easily add data. We didn’t consider thishere.

•We can use the interpolating polynomial to approximate, e.g.,∫ ba f (x) dx

•We looked at the freeware GNUPLOT for plotting data and functions.

• Now we ask ourselves if interpolating a large data set by a single polynomialis the best approach.

Page 34: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Runge’s Example

• Consider the function

f (x) =1

1 + 25x2− 1 ≤ x ≤ 1

which we want to interpolate (using only function values) with an increasingnumber of points. We interpolate with evenly spaced points.

-1 -0.5 0.5 1

0.5

1

1.5

2

-1 -0.5 0.5 1

-2

-1

1

2

3

4

-1 -0.5 0.5 1

0.2

0.4

0.6

0.8

1

-1 -0.5 0.5 1

-0.4

-0.2

0.2

0.4

0.6

0.81

Page 35: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

• As you can see, the interpolant gets more “wiggles” in it as it is required tointerpolate more points.

• It is for this reason that one should not use a single polynomial to interpolatea lot of data.

• The general rule is that

HIGH DEGREE POLYNOMIAL INTERPOLATION SHOULD BE AVOIDED

What can we do instead?

Page 36: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Piecewise Linear Interpolation

• Assume that we are given (x1, y1), (x2, y2), . . ., (xn+1, yn+1). We want toconstruct the piecewise linear interpolant. Graphically, all we do is connectthe points with straight lines.

Page 37: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

x1 x2 x3 xi xi+1 xn xn+1

• In general, we divide our domain into points xi i = 1, . . . , n + 1

• The piecewise linear interpolant on the interval [xi, xi+1] is just

Li(x) = ai + bi(x− xi)where

ai = yi yi+1 = yi + bi(xi+1 − xi)⇒ bi =yi+1 − yixi+1 − xi

Page 38: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

• Thus our piecewise linear interpolant is given by

L(x) =

L1(x) if x1 ≤ x ≤ x2

L2(x) if x2 ≤ x ≤ x3... ...

Li(x) if xi ≤ x ≤ xi+1

... ...

Ln(x) if xn ≤ x ≤ xn+1

• Note that L(x) is continuous but not differentiable everywhere.

Below we see some examples of piecewise linear interpolation for Runge’s exam-ple. Note that we no longer have the “wiggles” that occurred when the degreeof the polynomial got too large.

Page 39: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

-1 -0.5 0.5 1

0.2

0.4

0.6

0.8

1

-1 -0.5 0.5 1

0.2

0.4

0.6

0.8

1

-1 -0.5 0.5 1

0.2

0.4

0.6

0.8

1

Page 40: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Example

Use the piecewise linear interpolant to sinx on [0, π] using 2 equal subintervalsto evaluate it at x = π/3 and x = 3π/5. Compute the error.

• Our intervals are [0, π2 ] and [π2 , π].

• On the first interval the coefficients are

a1 = sin 0 = 0 b1 =sin π

2 − sin 0π2 − 0

=2

π

• On the second interval the coefficients are

a2 = sinπ

2= 1 b2 =

sin π − sin π2

π − π2

=0− 1π2

= −2

π

• The point π3 is in the first interval so

L1(x) = a1 + b1(x− x1)⇒ L1(π

3) = 0 +

2

π(π

3− 0) =

2

3The actual value of sin π

3 is 0.866025 so our error is approximately 0.2. Theerror is fairly large because the length of our subinterval is large π

2 ≈ 1.57.

Page 41: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

• Now the point 3π5 is in the second interval so

L2(x) = a2 + b2(x− x2)⇒ L2(3π

5) = 1− 2

π(3π

5− π

2) =

4

5The actual value of sin 3π

5 is 0.950157 so our error is approximately 0.151.

Page 42: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Implementing Piecewise Linear Interpolation

• Given the data (xi, yi), i = 1, 2, . . . , n+ 1, we can determine the coefficientsai, bi, i = 1, . . . , n on each of the n subintervals by the formulas

ai = yi bi =yi+1 − yixi+1 − xi

, i = 1, 2, . . . , n

This can be done once and stored just like we did for the coefficients in nthdegree interpolating polynomial.

• Unlike the case when we had a single nth degree polynomial, when we wantto evaluate our piecewise linear interpolant at some point x we have to decidewhich formula Li(x) we need to use. That is, we have to decide the subinterval[xi, xi+1] so that x ∈ [xi, xi+1]. Once we do this, then we simply use theformula ai + bi(x− xi) where our coefficients ai, bi are known.

Page 43: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Defining our Derived Data Type

Our data structure for continuous piecewise linear polynomials might have thefollowing attributes. This definition is analogous to our derived type for theLagrange form of the interpolating polynomial.

type pw linear inter

integer :: n points, n intervals

real(prec), pointer, dimension (:) :: x, y

real(prec),pointer, dimension(:,:) :: coefficients

end type pw linear inter

Recall that on each subinterval we have 2 coefficients (ai, bi) for linears so we

Page 44: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

have an array where the row number corresponds to the subinterval and the firstcolumn to ai and the second to bi.

If we used continuous piecewise quadratic interpolation we would have threecoefficients per interval. For cubics we have four.

Constructor to set the number of points and allocate arrays

•We choose to input the number of intervals.

•We will have routines called make linear, make quadratic, etc. whichwill set the number of points given the number of intervals and allocate theappropriate arrays.

• Keep in mind that the coefficients are defined over an interval, not over thenumber of points as in the Lagrange case.

• Number of points:

– Linear: number of points = number of intervals + 1

Page 45: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

– Quadratic: number of points = 2*number of intervals + 1

• Dimension of arrays

– poly % x and poly % y are one-d arrays dimensioned by the number ofpoints; of course we could have also chosen them to be stored in a 2-darray whose length is the number of points by two columns.

– The coefficients are stored in a two-d array

∗ Linear: allocate ( poly % coefficients( n intervals, 2 ) )

∗ Quadratic: allocate( poly% coefficients( n intervals, 3))

Page 46: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

function make linear (n int) result ( poly )

integer :: n int

type ( pw linear inter ) :: poly

poly % n intervals = n int

poly % n points = n int + 1

allocate ( poly % x(n int), poly % y(n int))

allocate ( poly % coefficients( n int,2 ) )

end subroutine make linear

Page 47: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Setting the evenly spaced x-coordinates of points to interpolate

•We said that we would write our code assuming that we want to interpolatea given function on a given interval.

• If we had discrete data instead, we could simply change this to a routine toread in the data.

• So the next step would be to set the xi values given the number of intervals,the left endpoint of the interval and its length. We will use evenly spacedpoints for simplicity.

•We will write a separate subprogram to do this and put it in our module. Ourroutine for linears could have the name

subroutine set xi linear (poly, x left, length)

• The executable statements for linears are basically what we have done before.

Page 48: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

n = poly % n intervals

deltax = length / float (n )

x = x left -deltax

do i = 1, poly % n points

x = x + deltax

poly % x (i) = x

end do

• To do quadratics, all we need to change above is instead of incrementing with

∆x we increment with∆x

2. Recall that the poly % n points already is

set to the total number of points.

Page 49: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Implementing the Coefficients

• Given the (xi, yi), i = 1, 2, . . . , number of points, we can determine thecoefficients of the polynomial on each subinterval from the given analyticformulas. This must only be done once.

Linear polynomials:

• Given the data (xi, yi), i = 1, 2, . . . , n+ 1, we can determine the coefficientsai, bi, i = 1, . . . , n on each of the n subintervals by the formulas

ai = yi bi =yi+1 − yixi+1 − xi

, i = 1, 2, . . . , n

• Recall that we stored our coefficients in an array dimensioned the number ofintervals by 2.

Page 50: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

subroutine compute linear coefficients ( poly )

type ( pw linear inter ), intent(inout) :: poly

integer :: n, i

real :: xi, xip1, yi, yip1

n = poly % n intervals

do i =1, n

xi = poly % x(i) ; xip1 = poly % x(i+1)

yi = poly % y(i); yip1 = poly % y(i+1)

poly % coefficients ( i, 1 ) = yi

poly % coefficients ( i, 2 ) = ( yip1 - yi ) / ( xip1 - xi)

end do

end subroutine compute linear coefficients

Page 51: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Evaluating the polynomial at a point

•When we want to evaluate our piecewise interpolant at some point x then wehave to decide which formula we need to use. That is, we have to decide thesubinterval.

• For linears this means we want to find i such that x ∈ [xi, xi+1]. Once we dothis, then we simply use the formula

ai + bi(x− xi)

where our coefficients ai, bi are known and stored in the ith row of poly %

coefficients.

• For linears we might have a function

evaluate linear polynomial ( poly, x, loc) result(pn at x)

where poly is a member of our piecewise linear class, x is the point weare evaluating at, and loc is the interval number which x is in. Then ourstatement which evaluates the appropriate linear polynomial is simply

Page 52: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

pn at x = poly % coefficients(1,loc) &

+ poly % coefficients(2,loc) * ( x - poly % x(loc) )

• So, unlike the situation where we just have one nth degree polynomial, herewe have a different polynomial over each subinterval. We have the additionalproblem of incorporating a search algorithm.

• The “brute force” approach to find the interval would be to loop from j = 1to j = n and check (assuming xj < xj+1 for all j) if x is less than rightendpoint (done if true) otherwise increment j. For linears this is just

do j =1,n

if ( x <= poly % x(j+1 ) ) then

i = j; exit ! x in [x j,x j+1]

end if

end do

• This is fine if we only have a few points but if we have a lot of points, or weare in higher dimensions, then it is costly.

Page 53: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

• A second approach is to exploit the monotonicity of the xi and to use a binarysearch, i.e., essentially the bisection method. We know that x1 ≤ x ≤ xn+1

and then we choose the middle xi (say xmid) and see if x1 ≤ x ≤ xmid orxmid ≤ x ≤ xn+1. We continue as in the bisection method approximatelyhalving the number of intervals where x is contained at each step.

• Note that in this case we are halving an integer which is our index on x. Thisis in contrast to the bisection method where we are halving a real number, thelength of the interval. So for example, if we have x ∈ [x1, x10] then we choosethe intervals [x1, x5], [x5, x10] (since (10−1)/2 = 4 in integer arithmetic) andthe first interval contains 5 nodes whereas the second contains 6 so since weare using integers we don’t always find a middle xi.

• For a random point x we really can’t do better than this binary search.

• However, if we are evaluating our interpolant at a set of points zj, j = 1,mwhere zj < zj+1 then it is more efficient to exploit the left-to-right orderingof the points.

• That is, if zj ∈ [xi, xi+1] then to find the location of zj+1 we first look in[xi, xi+1]. If it is not there then we look at the next interval to the right

Page 54: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

[xi+1, xi+2] and check to see if zj is in it; if it is not in second interval thenwe do a binary search on [xi+2, xn]. We will take a simplified approach andsimply check to see if it is in either of the two intervals to the right; otherwiseprint out an error message.

Page 55: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Search Algorithm

• As input we will send in the member of our piecewise polynomial data struc-ture, the point x, an initial guess for the interval containing x, and returnthe location, i.e., the interval which contains x. I wrote it so that the finallocation overwrites the initial guess for the interval. Using this strategy meanswe have to write a subroutine not a function.

• Before our loop to evaluate the polynomial at a point, we initialize the intervallocation to one, i.e., the first interval starting from the left.

Outline of search strategy

• Check to make sure x is in desired region

if ( x > poly % x(n points) .or. x < poly % x(loc) ) then

print *, "error: x not in given region", x,poly % x(loc),

poly % x(n points)

Page 56: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

stop

end if

• Now check to see if x is in the interval indicated by our initial guess

if ( x >= poly % x (loc ) .and. x <= poly % x (loc+1 ) )

then

return! in initial guess interval

• If it wasn’t in this interval then the next strategy is to check to see if it is inthe interval to the right of our initial guess

else if ( x >= poly % x (loc+1 ) .and. x <= poly % x (loc

+2 ) ) then

loc = loc +1 ! in next interval

return

• If x is not in the initial interval or the next interval to the right, then we checkthe next interval. If it is not in there we print out an error message and stop.

Page 57: n xi= 1;:::;n + 1 yi= 1;:::;n + 1 - Peoplejpeterson/Lecture_week10.pdf · ement) we might include its symbol (a character), its atomic number (an integer), its atomic weight (a real

Classwork

1. The module in class pw linear inter.f90 has the data structure defined,a constructor, outlines of the routines to calculate the coefficients and evaluatethe polynomial at a point, the search routine and the routine to calculate theevenly spaced points. Complete the routines to calculate the coefficients andevaluate the polynomial at a point given the interval it is in.

2. The driver program test pw linear inter.f90 is a skeleton code to testout the piecewise linear interpolant of f (x) = sin(x2). Put in the necessarycalls to the routines in the module and to compute the relative Euclidean errorin the piecewise linear interpolant.

3. Compare the error in the interpolant using 4, 8, 16, and 32 equal subintervals.Compare this with what you got for the Lagrange interpolating polynomial.