You are on page 1of 189

Advanced BASIC Scientific Subroutines

Other Macmillan titles of related interest


I. O. Angell Advanced Graphics with the IBM Personal Computer
A. N. Barrett and A. L. Mackay Spatial Structure and the Microcomputer -
Selected mathematical techniques
P. E. Gosling Practical BASIC Programming
K. McLuckie and A. Barber Sorting Routines for Microcomputers
Advanced BASIC
Scientific Subroutines

B. V. Cordingley
and
D. J. Chamund

M
MACMILLAN
EDUCATION
© B. V. Cordingley and D. J. Chamund 1988

All rights reserved. No reproduction, copy or transmission


of this publication may be made without written permission.

No paragraph of this publication may be reproduced, copied


or transmitted save with written permission or in accordance
with the provisions of the Copyright Act 1956 (as amended),
or under the terms of any licence permitting limited copying
issued by the Copyright Licensing Agency, 33-4 Alfred Place,
London WCIE 7DP.

Any person who does any unauthorised act in relation to


this publication may be liable to criminal prosecution and
civil claims for damages.

First published 1988

Published by
MACMILLAN EDUCATION LTD
Houndmills, Basingstoke, Hampshire RG21 2XS
and London
Companies and representatives
throughout the world
British Library Cataloguing in Publication Data
Cordingley, B. V.
Advanced BASIC scientific subroutines.
1. Science - Data processing 2. BASIC
(Computer program language).
I. Title II. Chamund, D. J.
502'.8'55133 Q183.9

ISBN 978-0-333-43569-4 ISBN 978-1-349-09282-6 (eBook)


DOI 10.1007/978-1-349-09282-6

Every c·are has been taken in the writing and testing of the programs contained in this book.
It has not been possible, however, to test the programs under all conditions and with the many
machines that are available. There will also be interaction between the user's own program and
the subroutines taken from this book. Users should therefore satisfy themselves that the oper-
ation of the programs and subroutines is suitable for the intended application. No liability for
any damage or injury that may result from the use of the material contained in this book can
be accepted by the authors or the publishers.
Contents

Preface viii

1 Introduction 1
1.1 Who Should Use this Book 1
1.2 BASIC, Style, Structure and Speed 1
1.3 The Subroutines and their Presentation 3
1.4 Syntax, Variables, Statements and Functions 4
1.5 Software and Rounding Errors 6
1.6 How to Use this Book 8

2 The Subroutines 9
2.1 Generation of Random Numbers 9
RNDBIN - Binomial random number generation 9
RNDPSN - Poisson random number generation 12
RNDNRM - Normal random number generation 15
RNDEXP - Exponential random number generation 18
2.2 Probability, Density and Distribution Functions 20
BINOPD - Binomial probability and distribution function 20
POISPD - Poisson probability and distribution function 22
NORMDT - Area under the normal curve 25
XPONDD - Exponential density and distribution function 29
LNGAMM - Natural logarithm of the complete gamma function 31
GAMMFN Ratio of the incomplete gamma function 34
BETAFN Ratio of the incomplete beta function 37
CHISQD Area under the chi-squared curve 42
FDISTR Area under the F-curve 45
TDISTR - Area under Student's t curve 47
2.3 General Statistics 50
MNVRNC Mean and variance 50
MAXMIN - Sorting data, percentiles and cumulative frequency
distribution 53
COMMNS t method of comparing the difference between two
means for paired and unpaired data 58
CONTIN - m x n contingency table with chi-squared test 64
PERCOM - Factorials, permutations and combinations 69

v
vi Contents

2.4 Analysis of Variance 72


OWAOVA - One-way analysis of variance 72
TWAOVA - Two-way analysis of variance with and without replicates 77
2.5 Linear Regression 87
MLNRG 1 - Summary statistics for regression 87
MLNRG2 - Determines values for the regression coefficients 87
MLNRG3 - Regression ANOVA table 87
MLNRG4 - Analysis of residuals 87
POLYRG - Polynomial and other linear regression 100
2.6 Matrix Operations 104
MAT ADD - Matrix addition 104
MATSBT - Matrix subtraction 104
MATTRN - Matrix transposition 104
MATCNT - Matrix multiplication by a constant 104
MATMUL - Multiplication of two matrices 104
MATRED - Reads a matrix from a DATA statement 104
MATWRT - Prints a matrix 104
MATEGN - Computes eigenvalues and eigenvectors of a real
symmetric matrix 114
MATINV Inverts a matrix 119
MATDET Finds the determinant of a matrix 119
2.7 Interpolation 125
INTPLN Interpolation by the Lagrange polynomial method 125
2.8 Numerical Analysis 128
CHBSHV - Generates a Chebyshev polynomial 128
FURIER - Fourier series used to approximate observed periodic data 133
2.9 Calculus 138
DIFEQ1 - Numerical solution of a 1st-order differential equation 138
DIFEQ2 - Numerical solution of a 2nd-order differential equation 138
TRPZDL - Numerical integration of a function by the trapezium
rule 145
SIMPSN - Numerical integration of a function by Simpson's rule 145
INTDAT - Integration of numerical data by Simpson's rule 145
2.10 Solution of Equations 151
SOLUTN Analytical solution of a system of N linear equations
with N unknowns 151
QADEQN Finds the two roots of a quadratic equation by an
analytical technique 154
CUBEQN Finds the three roots of a cubic equation by an
analytical technique 157
NEWITR Numerical solution of an equation by Newton's
method 162
BISECT Numerical solution of an equation by the method of
bisection 162
Contents vii

2.11 Complex Numbers 167


COMPLX - Performs addition, subtraction, multiplication and
division of two complex numbers. Finds the reciprocal,
square, polar and non-polar forms of a single complex 167
number

References 174

Index 176

Details of Associated Software 179


Preface

The use of computers today for scientific and engineering purposes is commonplace.
School pupils studying science·based subjects will almost certainly have had some
hands-on experience of computing by the time they are ready to sit their final
examinations. Those leaving university with a science or engineering degree are
likely to have a working knowledge of more than one high-level language.
In the mid 1960s computer programming was just beginning to feature in the
syllabuses of some undergraduate courses. The emphasis on programming at that
time was to save memory, increase speed and if possible make the program code
understandable to the author and perhaps even other users. Advances in micro-
electronics have today made possible the production of machines of such memory
capacity and speed that under many conditions of use, memory space limitations
and computing time place little constraint on the programmer. The current emphasis
is on structure and style of programming.
What has not changed so dramatically is the effort required to design and develop
computer software, and this is reflected in the changes in the relative costs of soft-
ware and hardware over the same interval. Every machine requires software to drive
it, and for large jobs or tasks of a specialist nature there is probably no real alterna-
tive to the purchase of commercial software or its production by those highly
proficient in this task. Commercial software, however well written, is likely to
suffer from several limitations: it is first of all expensive; it tends to be machine
specific and so can suffer from limited portability and is often accompanied by
copyright restrictions; it is rigid and not generally amenable to modification by the
user and input and output are predetermined. The software, to obtain wider market-
ability, is often far more powerful and consequently complex than the user requires.
If it has to be purchased, then the right type of software has to be found and
studied - all points that make it difficult to justify for those smaller jobs. It is these
and other limitations that contribute towards the reasons why many engineers and
scientists write some software themselves - the need to do this is implicitly recog-
nised by the proportion of time devoted to this task in the formal training that they
currently receive.
What we have attempted to do in this book is to provide a collection of sub-
routines which can function as the building blocks for scientific programs of the
user's own creation. We have written them in a uniform style and presented them
in a manner which we anticipate will make them easy to use. BASIC has been

viii
Preface ix

selected as we believe it is the language with which potential readers are still most
likely to be familiar and the one that will be compatible with their computer both
at home and in the workplace.
One of the problems encountered in compiling a book of this nature is to know
what material to include and what to exclude. Subroutines which would be relevant
but which only occupy a few lines of code and which also are likely to cause no
problem to the user have been omitted, as have those which would be regarded as
trivial by the anticipated readership. Other work has had to be eliminated through
restrictions on space, or because it was thought to be too narrow in its application.
We have attempted to retain only what we consider to be the most generally useful
material.
In the preparation of this book, help has been received from several sources.
Here we should like to acknowledge with gratitude the assistance of Michael J.
Morris of the School of Economic and Social Studies, University of East Anglia;
Martin Wilson of the Department of Statistics and Operational Research, Coventry
Polytechnic, for assistance with the details of some of the statistical subroutines;
and Juliet Davison for her help in kindly typing the manuscript.
1 Introduction

1.1 Who Should Use this Book

A quick skim through the pages of this book will reveal its nature - it is principally
a library of subroutines written in BASIC which would find use in the solution of
many engineering and scientific problems.
The subroutines contained in this publication have been designed for use by
students who are studying mathematics and statistics in preparation for university
entrance and who have an interest in scientific computing. The subroutines are also
intended for use by undergraduates who are pursuing science or engineering studies
at university and for practising engineers and scientists who do at least a proportion
of their own programming. It is anticipated that these groups of individuals are
likely to have access to small personal or home computers and occasional use of
larger machines. Previous experience of writing programs containing subroutines
will be required if the reader is to make full use of this book.
Mathematics and statistics are difficult subjects and no attempt is made to teach
them here. There are many excellent books on these topics and we feel that dupli·
eating the work in this volume would be both unnecessary and inappropriate.
Similarly, this is not a text on BASIC programming; for readers who wish to brush
up their BASIC we can recommend Practical BASIC Programming (Gosling, 1982).

1.2 BASIC, Style, Structure and Speed

BASIC is the most widely available high-Ievellanaguage and is supplied for the
overwhelming majority of modern small computers, as well as being provided on
larger machines. It remains likely to be the language first studied by those learning
programming. BASIC is easy to use and, because it is usually entered via an inter·
preter, program development is assisted by the availability of excellent fault diag-
nostics. The facilities available with the BASIC language are continually being
enhanced. It is an endorsement of BASIC that it is the language chosen for writing
a significant amount of professional scientific software.
The BASIC language is still changing and evolving. Procedures are included
among the more powerful features now being introduced but this facility is not
sufficiently widely available at the present time to make it appropriate to use them
in this book. The more experienced programmers should find it a relatively easy

1
2 Advanced BASIC Scientific Subroutines

task to rewrite the subroutines as procedures in a form suitable for their machines.
The detractors of BASIC for use in scientific programming argue principally
that the language lacks 'structure' and favour FORTRAN, C and sometimes ALGOL,
or more commonly today, Pascal. It would be perverse to deny that there is some
weight in the argument. Nevertheless, structure is not an absolute but rather a
question of degree - it is possible to write programs of reasonable structure in
BASIC. Also the degree of 'structure', despite its importance, is only one of several
criteria on which the suitability of a programming language is to be judged. The
attributes of BASIC (wide availability, ease oflearning and advanced facilities to
aid the testing and modification of programs) will take some defeating and, collec-
tively, are arguably superior to those possessed by other languages.
We have attempted to achieve a reasonable degree of 'structure' in the design
of the subroutines, that is, as far as we believe is reasonable within the constraints
imposed by today's commonly available versions of BASIC. For example, we have
tried to keep the length of individual subroutines well within a page and have
restricted the use of GOTO as much as possible. Where this statement is employed,
the direction is forward in the program whenever practical. Only one RETURN
statement is present in each subroutine.
The style of presentation is largely after that given in the book The Little Book
of BASIC Style (Nevison, 1978) and we can recommend this work to those who
write a significant number of programs in BASIC. In writing the subroutines we
have generally given clarity priority over the demands of speed and memory. It was
necessary to reproduce the program listings in this book at a size which would
facilitate the task of entering them manually into a computer. To satisfy this
requirement the number of characters per line has been restricted to 57.
At first glance the printed code may appear to be somewhat over 'REMed'
and spaced. The reader will no doubt feel free to compact the programs, indeed
software is available for several machines specifically to accomplish this task. The
reverse process however, is not so readily achieved. It is, nonetheless, probably
best to leave this exercise until the programmer is satisfied that correct operation
has been established.
On occasions, it will be necessary to increase the speed at which a program runs.
For example, if a subroutine has to be called many times by the main program, as
could happen in a simulation exercise, increases in speed could be beneficial. Pro-
gramming method, presentation, the machine and its employment of BASIC all
combine to determine the speed at which a program runs. Handbooks supplied
with computers generally contain hints on how speed may be increased, such as by
the removal of lines containing REM statements, general compaction of the pro-
gram and the introduction of multiple-statement lines. Increases in speed are often
gained at the expense of clarity and therefore they need to be justified.
Introduction 3

1.3 The Subroutines and their Presentation

The great worth of subroutines is found in their flexibility. They impose no restric-
tions on input and output data format and they may be tested independently of
the main program. A common subroutine may be used in several programs. Sub-
routines form the building blocks from which large programs are constructed.
At the heart of many subroutines is an algorithm which performs the mathe-
matical task allotted. It takes the information required from the host program and
returns the information that the host requires in its turn. There are several ways of
writing an algorithm to generate the required results, and perhaps by the exercise
of greater ingenuity and wisdom the reader may well be able to improve on our
efforts. Alterations which merely improve speed at the expense of clarity should
be closely examined for their value.
A few words of explanation on the various headings under which the subroutines
are described may prove helpful here:

Description - Provides a brief outline of the function of the subroutine and men-
tions any other subroutines required.
Subroutine - In BASIC, subroutines are called by their line number. As line number
references are more difficult for humans to relate to than are descriptive names,
each subroutine is given a six letter name which is 'called' just prior to the GOSUB
statement in the main program (a technique adapted from FORTRAN).
Method - Under this heading is given a brief description of the mathematical
method employed and a guide to the operation of the subroutine. The subroutines
have been written to be used essentially as 'black boxes'. The brief description of
the method of operation is included, not so much as a teaching aid in itself, but
rather to remove ambiguity that may exist over the use of certain mathematical
terms. It also serves to facilitate further study of the subject should this be desired.
References are supplied in support of more unusual procedures, or where infor-
mation on the mathematical method may not be found readily.
Subroutine listing - The listing of the subroutine usually (though not always) starts
with the line number 2000 and each line is incremented by 10. In many applications
it will be desirable to change the line numbers employed for the subroutine, such as
when more than one subroutine is used within the same program. The subroutine
itself contains introductory REM statements which further indicate its application
and define input and output variables, together with instructions on the minimum
sizes required by arrays.
Sample program - Each subroutine is accompanied by at least one sample program
which it is intended primarily to be of assistance in constructing the tests that the
user will wish to conduct. These examples may not appear to be directly relevant
to the user's intended application, but the number of potential uses for many of
the subroutines is legion and a large number of examples would be required to
reflect these adequately.
4 Advanced BASIC Scientific Subroutines

In addition to demonstrating the manipulation of the input and output data,


the sample program illustrates the minimum array space required for the solution
of a particular problem. Data, when required, is usually read from a DATA state-
ment in the host program.
The output is printed together with a small amount of text to aid understanding.
Whereas this is satisfactory for the purposes of demonstration and trial runs, it
would be expected that software produced by the reader for general use would
contain rather more descriptive output, with perhaps some graphics. The number
of significant figures presented, and their format, are set by the machine used to
generate the printout, and these instructions are not included in the sample
program. The user operating in default mode is likely to observe a different
number of significant figures produced on trial runs. To obtain hard copy printout,
PRINT needs to be replaced by LPRINT on many machines.
Notes - Additional points on error detection and accuracy are included under
this heading together with other observations that may be of interest.

1.4 Syntax. VariDbles. Statements and Functions

Portability has been a primary consideration in preparing the subroutines and


sample programs for this book. Nevertheless, it was felt to be unnecessarily restric-
tive to adhere rigidly to anyone standard BASIC (such as American National
Standard (ANSI, 1978» and some widely available extensions to the language
have been incorporated. Advanced features which are not generally available have
not been exploited.
The programs and subroutines have been written to work without significant
modification on machines which run with IBM versions of the BASIC language;
these include the IBM PC range, the Amstrad PC 1512 and other IBM compatibles.
They will also work with minimal adaptation with the BASIC supplied with the
BBC micro, the Sinclair Spectrum and the Hewlett-Packard 86 and 86B. They
should also run on many more machines with only minor modification. The
machine's interpreter should quickly identify variations. The only modifications
required in many cases are simply to change the function used to call the machine's
uniform random number generator that is employed in some of the statistical
programs and to exchange the function LN for LOG.
A few further points are made below.

Syntax

Upper-case letters have been used throughout. Output has been restricted to what
can be achieved with simple PRINT statements. As graphical output tends to be
very machine specific and subject to personal preference, we did not feel it
appropriate to include this in the sample programs. Subroutines to generate
graphical output were felt to be outside the scope of this book. Those requiring
Introduction 5

access to subroutines on this subject are referred to books by Angell and Jones
on graphics (Angell and Jones, 1983a, 1983b; Angell, 1985).
Multiple·statement lines and multiple assignment statements have both the
capacity to simplify and confuse programs: however, because of their restricted
availability, these facilities have not been exploited and each line of program
contains one instruction only.

Variables

Descriptive names have been employed where this is felt to aid understanding.
The maximum number of letters used in any variable name is six. Some earlier
versions of BASIC require that the variable name be defined by the first two
characters and users of these will have to accommodate this requirement by
selecting their own variable names. Also, some machines will not permit reserved
BASIC words to be included at the beginning of variable names; this restriction
has been accepted and may superficially give the impression of some idiosyncrasy
in the choice of names for several variables.
Integer variables are not used in this work and string variables only on a few
occasions. String variables are terminated with the '$' character. Array variables
are given single letter names.
The subroutines contain a list of global and local variables. Global variables
are used to communicate input and output values between the main program (and
sometimes other subroutines) and the subroutine. A local variable has a function
purely within a subroutine; it may be used within the main program, but caution
should be exercised as execution of the subroutine is likely to affect its value.

Statements

DIM - It is assumed that the size of the array must be declared before it is used
and that a variable may not be employed for this task; that is, DIM B(78) is
acceptable, but DIM B(NUMOBS) is not. Indications on the minimum array
sizes to be specified are contained within the subroutines and employed in the
sample programs. Except in the case of programs in which space is likely to
impose constraints (for example, those involving regression techniques and analysis
of variance), it is satisfactory to continue the generally accepted practice of safely
over-specifying the size of array required.

END - is necessary to denote the end of a program. Subroutines come below END
in the sample programs. STOP is not used, though it may be substituted for END
where the END statement is not available. END is also used within some sub-
routines to terminate the program if a major error is discovered.

FOR-NEXT - The word STEP is omitted if its value is unity. P, Q, R and S are
used as control variables in the subroutines (and are included under the heading
6 Advanced BASIC Scientific Subroutines

of Local variables). This leaves the usual control variables I, J, K, L, M and N for
use in the sample program and the user's main program without overmuch
thought.

LET - is employed when assigning a value to a variable. On most modern versions


of BASIC its use is optional.

IF-THEN - The word THEN, although optional in some versions of BASIC, is


included in the listings.

IF-THEN-ELSE - The word THEN is included.

IF-THEN GOTO - The optional word GOTO is included in the listings.

Functions

DEF FN - is used to define a user-defmed function. The defmition is limited to


one line of code and the name restricted to a single letter, for example,
DEF FNA(X) = X 3. A

FN - Preceding a single-letter variable name is used to call a user-defined function.

LN - Returns the natural logarithm of a number. Note that many versions of


BASIC employ LOG (including IBM versions) for the natural logarithm, whereas
others reserve it for the logarithm to base 10 (for example, BBC BASIC).

RND(-l) - is used to reseed the uniform random number generator. This is useful
if the same set of random numbers is required each time a program is run - for
example, in diagnostic work. A programmer will have to consider whether a
constant or new set of random numbers is required each time a program is run and
then select the desired function from the machine's library.

RND(l) - Generates a uniformly distributed random number between 0 and 1.

1.5 Software and Rounding Errors

Software errors can be conveniently divided into three categories: those which are
identified during the interpretation of the program; those which occur during the
running of the program; and logical errors which produce erroneous results.
The BASIC language interpreter makes identification of syntax and run-time
errors reasonably straightforward. Errors identified may be patently errors in code
entry or perhaps an incompatible form of BASIC. Run-time errors give a line
number at which the error was spotted. If this is found to be in the section of the
program written by the reader, then a customary procedure for debugging should
Introduction 7

be enacted. If it occurs in the subroutine then the input data should be checked
to ensure that it is sensible. If this is found to be satisfactory then the code
entered for the subroutine should be double-checked.
The most difficult errors are those which produce wrong results and, as when
writing their own software, readers should test that their programs give sensible
output. The degree of testing that can be justified must, of necessity, be left to
the programmer's discretion.
The most common causes of inaccuracy having their origins inside the sub-
routine include:

Inappropriate BASIC - for example, misinterpreting the LOG function.

Inadequate precision - rounding errors producing incorrect results.

Inappropriate technique - such as use of regression to solve simultaneous equations


or numerical integration on discontinuous functions.

Working beyond the limitations of the method - solution of ill-defmed equations


come into this category. Another example would be numerical integration by
means of Simpson's rule, where uniform steps would fail to cope with sudden
localised changes in function value.

Bugs in the subroutines - although these subroutines have been checked under a
wide variety of conditions, they clearly have not been tested with all machines,
nor with multitudinous driver programs, nor with all possible input data. They
were written by humans and it would be arrogant to presume that all of them are
totally free of error.

The computer printouts presented in this book have been reproduced photo-
graphically and therefore the copying process itself should not be responsible for
the introduction of mistakes.
Many of the subroutines do contain some rudimentary mechanisms to facilitate
error identification which serve to warn the user of possible failure or where
failure has occurred. However, notWithstanding other difficulties, to include the
extensive error detection necessary to cover every contingency would occupy
much space and add considerably to complexity. Error checks have been mini-
mised or omitted altogether where their use is likely to cause real increases in
run time (for example, in subroutines likely to be used in simulation exercises).
Readers must decide for themselves the degree of checking and testing that is
necessary according to their habit and requirements.
8 Advanced BASIC Scientific Subroutines

1.6 How to Use this Book

The effort applied and the method adopted when writing a program will depend on
its intended application and purpose. The approach selected for a one-off program
will clearly be different from that chosen for work which is going to form part of
some software for a laboratory or which is likely to be modified later by others.
Work on programs being developed with the aid of this book may proceed along
the following lines:

(a) Define the problem and its method of solution.


(b) Decide on input and output requirements and format and select the sub-
routine to be employed.
(c) Enter the subroutine and a companion sample program, exactly as printed in
this book.
(d) Check that this combination runs correctly and produces results acceptably
close to those contained in the sample output. Some numerical results -
particularly those involving random number generation - may be expected
to be somewhat different from those presented in the text. If the program
fails to run correctly, make any necessary modifications dictated by the
version of BASIC employed and correct any entry errors.
(e) Once the subroutine and sample program run correctly, renumber the lines
as required.
(f) Delete the sample program and save the subroutine.
(g) Write the driver program with output format just sufficient to produce sample
results.
(h) Merge the subroutine.
(i) Run and check results.
G) Embellish input and output format and run.
(k) Repeat G) until the required form is established.
(1) Check the program under the extremes of conditions that are likely to be
observed in practice and check output.
(m) Add error detection facilities as required.
(n) If the program runs too slowly, make modifications to increase speed and
recheck performance.
(0) Tidy program and renumber as appropriate and retest.
(p) Produce any supporting documentation that is felt to be desirable.
2 The Subroutines

2.1 Generation of Random Numbers

GENERATION OF A BINOMIALLY-DISTRIBUTED RANDOM NUMBER

Subroutine: RNDBIN

Description

Generates random numbers with a binomial distribution with parameters n and p.

Method

The binomially-distributed random variable X is given by


n
X= ~ B;
;=1

where n is the number of trials and p the probability of a success on a single trial.
B; are independent random variables which take the value 1 with probability p
and 0 with the probability 1 - p.

Subroutine Listing

2000 REM BINOMIALLY-DISTRIBUTED RANDOM NUMBERS


2010 REM
2020 REM SUBROUTINE: RNDBIN
2030 REM
2040 REM XBIN IS A BINOMIALLY-DISTRIBUTED RANDOM
2050 REM NUMBER WITH PARAMETERS PSCCSS AND NUMTRL.
2060 REM RND(l) GENERATES UNIFORMLY-DISTRIBUTED
2070 REM RANDOM NUMBERS IN THE RANGE 0 TO 1
2080 REM
2090 REM VARIABLES:
2100 REM INPUT:
2110 REM NUMTRL .. NUMBER OF TRIALS

9
10 Advanced BASIC Scientific Subroutines

2120 REM PSCCSS .. PROBABILITY OF A SUCCESS


2130 REM ON A SINGLE TRIAL
2140 REM OUTPUT:
2150 REM XBIN .... BINOMIALLY-DISTRIBUTED
2160 REM RANDOM NUMBER
2170 REM LOCAL: ... P, XUNI
2180 REM
2190 LET XBIN = 0
2200 FOR P = 1 TO NUMTRL
2210 XUNI = RND(l)
2220 IF XUNI <= PSCCSS THEN LET XBIN XBIN + 1
2230 NEXT P
2240 RETURN

Sample Program

If five dice are thrown 10000 times, estimate by simulation the number of times
three or more sixes will occur.

1000 REM SAMPLE PROGRAM: PRNDBIN


1010 REM
1020 REM FINDS THE NUMBER OF TIMES N1 OR MORE SIXES
1030 REM OCCUR IF N2 DICE ARE THROWN NUMSIM TIMES
1040 REM
1050 REM VARIABLES:
1060 REM N1 ....... MIN. NUMBER OF SIXES
1070 REM N2 ....... NUMBER OF DICE THROWN
1080 REM NUMSIM ....... NUMBER OF THROWS
1090 REM TSCCSS ... NUMBER OF SUCCESSES
1100 REM X........ UNIFORM RANDOM NUMBER U(O,l)
1110 REM
1120 REM SET INITIAL VALUES
1130 LET N1 = 3
1140 LET N2 = 5
1150 LET NUMSIM 10000
1160 LET NUMTRL N2
1170 LET PSCCSS 1/6
1180 LET TSCCSS = 0
1190 LET X = RND(-l)
1200 REM
1210 REM COUNT NUMBER OF TIMES XBIN >= N1 IN 10000
1220 REM CALL SUBROUTINE RNDBIN 10000 TIMES
1230 FOR I = 1 TO NUMSIM
1240 GOSUB 2000
1250 IF XBIN >= N1 THEN LET TSCCSS = TSCCSS + 1
1260 NEXT I
1270 PRINT" THE NUMBER OF SUCCESSES IS "; TSCCSS
1280 END

>RUN
THE NUMBER OF SUCCESSES IS 345
The Subroutines 11

The expected number of times three or more sixes would be thrown in 10000
throws is 354.9 (see sample program on binomial probability and distribution
function).

Note

As with other simulation exercises, the value obtained by running the sample
program will depend on the machine and the initial value of the uniform random
number generator.
12 Advanced BASIC Scientific Subroutines

GENERATION OF A POISSON-DISTRIBUTED RANDOM NUMBER

Subroutine: RNDPSN

Description

Generates random numbers with a Poisson distribution of mean value L.

Method

A Poisson random number may be generated with the aid of an exponential


random number generator by considering the number of events that occur in
unit time. For a Poisson distribution with parameter L, the mean time for an
event is I/L.
The time taken for the first event Tl to occur is

where U 1 is a random variable with a U(O, 1) distribution (see subroutine


RNDEXP).
The time for n events is

Tn = -(I/L)ln (ii
1=1
Ui)

To generate the Poisson random number the value of n is incremented until


Tn exceeds unity; that is, the condition

-{l/L)ln (~1 U~ >1

must be satisfied. Some re-arrangement improves the efficiency of computation:

In(ii1=1
U1' <-L
')

n
IT Uj < EXP(-L)
1=1

The smallest value of n for which this condition is satisfied has a Poisson dis·
tribution of parameter L.
A further deSCription of this technique is given by Morgan (Morgan, 1984)
The Subroutines 13

Subrouting Listing

2000 REM POISSON-DISTRIBUTED RANDOM NUMBER


2010 REM
2020 REM SUBROUTINE: RNDPSN
2030 REM
2040 REM XPSN IS A RANDOM NUMBER WITH A POISSON
2050 REM DISTRIBUTION OF PARAMETER L1
2060 REM RND(l) GENERATES UNIFORMLY-DISTRIBUTED
2070 REM RANDOM NUMBERS IN THE RANGE 0 TO 1
2080 REM
2090 REM VARIABLES:
2100 REM INPUT:
2110 REM VEXPL1 .. EXP(-L1) WHERE L1 IS POISSON MEAN
2120 REM OUTPUT:
2130 REM XPSN .... POISSON-DISTRIBUTED RANDOM NUMBER
2140 REM LOCAL: ... TSUM
2150 REM
2160 LET TSUM = RND(l)
2170 LET XPSN = 0
2180 IF TSUM < VEXPL1 THEN GOTO 2220
2190 LET TSUM TSUM*RND(l)
2200 LET XPSN = XPSN + 1
2210 GO TO 2180
2220 REM
2230 RETURN

Sample Program

The telephone operators at a large switch board have to deal with telephone calls
at an average rate of2 per minute. Assuming the process can be represented by a
Poisson distribution, estimate, by simulating 10 000 one-minute intervals, the
probability of 1, 2, 3, 4 or 5 calls arriving within a one-minute interval.

1000 REM SAMPLE PROGRAM: PRNDPSN


1010 REM
1020 REM DETERMINES THE PROBABILITY OF BETWEEN N1
1030 REM AND N2 EVENTS OCCURRING IN ONE MINUTE
1040 REM GIVEN THAT THE PROCESS HAS A POISSON
1050 REM DISTRIBUTION OF MEAN L1 PER MINUTE
1060 REM
1070 REM VARIABLES:
1080 REM N1 ......• MIN. NUMBER OF EVENTS
1090 REM N2 ••...•. MAX. NUMBER OF EVENTS
1100 REM NUMSIM ..• NUMBER OF SIMULATIONS
1110 REM TEVENT ..• TOTAL NUMBER OF EVENTS IN RANGE
1120 REM X•.••..•. UNIFORM RANDOM NUMBER U(O,l)
1130 REM
1140 REM SET INITIAL VALUES
14 Advanced BASIC Scientific Subroutines

1150 LET Ll = 2
1160 LET Nl = 1
1170 LET N2 = 5
1180 LET NUMSIM = 10000
1190 LET TEVENT = 0
1200 LET VEXPLI = EXP(-LI)
1210 LET X = RND(-l)
1220 REM
1230 REM COUNT NUMBER OF TIMES NI <= XPSN <= N2
1240 REM CALL SUBROUTINE RNDPSN NUMSIM TIMES
1250 FOR J = 1 TO NUMSIM
1260 GOSUB 2000
1270 IF XPSN < HI OR XPSN > N2 THEN GOTO 1290
1280 LET TEVENT = TEVENT + 1
1290 REM
1300 NEXT J
1310 PRINT" PROBABILITY OF BETWEEN "; Nl; " AND "; N2
1320 PRINT" CALLS = "; TEVENT/NUMSIM
1330 END

>RUN
PROBABILITY OF BETWEEN 1 AND 5
CALLS = 0.8491

This value of 0.8491 should be compared with 0.8481 which is obtained by


direct calculation (see sample program on Poisson probability and distribution
function).
The Subroutines 15

GENERATION OF A NORMALLY-DISTRIBUTED RANDOM NUMBER

Subroutine: RNDNRM

Description

Generates pairs of random numbers which are normally distributed with mean
and variance 1,N(O, 1)
°
Method

This method of generating normally-distributed random numbers is described by


Morgan (Morgan, 1984). It is based on what has become known as the 'Polar
Marsaglia' method.

°
If U 1 and U2 are two independent random variables uniformly distributed
between and 1, U(O, 1), and
Vi =2U1 -1, V2 =2U2 -1 and
R2 = V~ + VLR 2 < 1 (R2 rejected otherwise)
then
Nl = V2((-2InR2)/R2)t and
N2 = Vl((-2InR2)/R2)t
where Nl and N2 are independent variables with a N(O, 1) distribution.

Subroutine Listing

2000 REM NORMALLY-DISTRIBUTED RANDOM NUMBERS


2010 REM
2020 REM SUBROUTINE: RNDNRM
2030 REM
2040 REM XNRM1 AND XNRM2 ARE NORMALLY DISTRIBUTED
2050 REM RANDOM NUMBERS OF MEAN 0 AND VARIANCE 1
2060 REM GENERATED BY THE POLAR-MARSAGLIA METHOD.
2070 REM RND(l) GENERATES UNIFORMLY-DISTRIBUTED
2080 REM RANDOM NUMBERS IN THE RANGE 0 TO 1
2090 REM
2100 REM VARIABLES:
2110 REM INPUT:
2120 REM NONE
2130 REM OUTPUT:
2140 REM XNRM1 .... NORMALLY-DISTRIBUTED RANDOM
2150 REM XNRM2 RANDOM NUMBERS, N(O,l)
2160 REM LOCAL: .... V1, V2, V3, V4
2170 REM
2180 LET V1 2*RND(1) - 1
2190 LET V2 = 2*RND(1) - 1
16 Advanced BASIC Scientific Subroutines

2200 LET V3 = V1*V1 + V2*V2


2210 IF V3 > 1 THEN GOTO 2170
2220 LET V4 = SQR«-2*LN(V3»/V3)
2230 LET XNRM1 = V1*V4
2240 LET XNRM2 = V2*V4
2250 RETURN

Sample Program

Determine the area under the standard normal curve,N(O, 1) - 0 0 to t for


t = -2, -1.5, -1, -0.5,0,0.5,1,1.5,2 by a method based on the generation of
10OOO,N(O, I) random numbers.

1000 REM SAMPLE PROGRAM: PRNDNRM


1010 REM
1020 REM CALCULATES THE AREA UNDER THE NORMAL CURVE
1030 REM FROM MINUS INFINITY TO T BY SIMULATION
1040 REM
1050 REM VARIABLES:
1060 REM A() ...... NUMBER NORMAL RANDOM NUMBERS <= T
1070 REM N1 ....... 0.5*RANDOM NUMBERS GENERATED
1080 REM N2 ....... NUMBER OF VALUES OF T
1090 REM T() ...... VALUE OF T
1100 REM X•....... UNIFORM RANDOM NUMBER U(O,l)
1110 REM ARRAY DIMENSIONS:
1120 DIM A(9)
1130 DIM T(9)
1140 REM
1150 REM SET INITIAL VALUES
1160 LET X = RND(-l)
1170 LET N1 = 5000
1180 LET N2 = 9
1190 FOR I = 1 TO N2
1200 LET T(I) = I/2 - 2.5
1210 LET A(I) = 0
1220 NEXT I
1230 REM
1240 REM GENERATE NORMALLY-DISTRIBUTED RANDOM NUMBERS
1250 REM CALL SUBROUTINE RNDNRM N1 TIMES
1260 FOR I = 1 TO N1
1270 GOSUB 2000
1280 FOR J = 1 TO N2
1290 IF XNRM1 <= T(J) THEN LET A(J) = A(J) + 1
1300 IF XNRM2 <= T(J) THEN LET A(J) = A(J) + 1
1310 NEXT J
1320 NEXT I
1330 PRINT" T AREA"
1340 FOR I = 1 TO N2
1350 PRINT T(I), A(I)/(2*N1)
The Subroutines 17

1360 NEXT I
1370 END

>RUN
T AREA
-2 2.12E-2
-1.5 6.31E-2
-1 0.1556
-0.5 0.3146
o 0.5008
0.5 0.6931
1 0.8448
1.5 0.93
2 0.9762

These results are to be compared with those published in tables on the standard
normal curve. These are: 0.02275,0.06681,0.1587,0.3085,0.5000,0.6915,
0.8413,0.9332 and 0.9773 respectively.
18 Advanced BASIC Scientific Subroutines

GENERATION OF AN EXPONENTIALLY-DISTRIBUTED RANDOM NUMBER

Subroutine: RNDEXP

Description

Generates random numbers with an exponential distribution of parameter Land


mean I/L.

Method

In general, random variables may be transformed with the aid of the relationship
fx(x) =fu(u) I du/dx I
If X = -(l/L)ln(U) where U is a uniformly-distributed random variable with a
U(O, 1) distribution, andfu(u) = 1 for 0 < u < 1 then
fx(x) = 1. I-L.EXp( -Lx) I
=L.EXP(-Lx)
which is an exponentially-distributed random variable.

Subroutine Listing

2000 REM EXPONENTIALLY-DISTRIBUTED RANDOM NUMBER


2010 REM
2020 REM SUBROUTINE: RNDEXP
2030 REM
2040 REM XEXP IS A RANDOM NUMBER WITH AN EXPONENTIAL
2050 REM DISTRIBUTION OF PARAMETER Ll AND MEAN llLl
2060 REM RND(l) GENERATES UNIFORMLY-DISTRIBUTED
2070 REM RANDOM NUMBERS IN THE RANGE 0 TO 1
2080 REM
2090 REM VARIABLES:
2100 REM INPUT:
2110 REM Ll ...... WHERE llLl IS THE MEAN
2120 REM OUTPUT:
2130 REM XEXP .... EXPONENTIALLY-DISTRIBUTED
2140 REM RANDOM NUMBER
2150 REM
2160 LET XEXP = -LN(RND(l))/Ll
2170 RETURN

Somple Program

The mean time to failure of a certain device is two years (or an average rate of
0.5 failures per year). By conducting 10 000 simulations, estimate the probability
The Subroutines 19

that at least one failure will occur in four years. The failure process has an expo-
nential distribution.

1000 REM SAMPLE PROGRAM: PRNDEXP


1010 REM
1020 REM GIVEN THAT FAILURES OCCUR ON AVERAGE AT
1030 REM 1/L1 PER UNIT TIME DETERMINE THE PROBABILITY
1040 REM THAT IT IS NO MORE THAN N1 UNITS OF TIME
1050 REM TO THE FIRST FAILURE.
1060 REM
1070 REM VARIABLES:
1080 REM N1 ...•..• TIME TO FIRST FAILURE
1090 REM NUMSIM .•. NUMBER OF SIMULATIONS
1100 REM TEVENT ... TOTAL NUMBER OF EVENTS
1110 REM X....•.•• UNIFORM RANDOM NUMBER U(O,l)
1120 REM
1130 REM SET INITIAL VALUES
1140 LET L1 = 0.5
1150 LET N1 = 4
1160 LET NUMSIM = 10000
1170 LET X = RND(-l)
1180 LET TEVENT = 0
1190 REM
1200 REM COUNT NUMBER OF TIMES XEXP < N1 AND
1210 REM GENERATE EXPONENTIAL RANDOM NUMBER
1220 REM CALL SUBROUTINE RNDEXP NUMSIM TIMES
1230 FOR J = 1 TO NUMSIM
1240 GOSUB 2000
1250 IF XEXP <= N1 THEN LET TEVENT = TEVENT + 1
1260 NEXT J
1270 PRINT" PROBABILITY FAILURE OCCURS IN FIRST "; N1
1280 PRINT" TIME UNITS IS "; TEVENT/NUMSIM
1290 END

>RUN
PROBABILITY FAILURE OCCURS IN FIRST 4
TIME UNITS IS 0.8618

This answer of 0.8618 should be compared with the expected value of 0.8647
which is obtained by direct calculation.
20 Advanced BASIC Scientific Subroutines

2.2 Probability, Density and Distribution Functions

BINOMIAL PROBABILITY AND DISTRIBUTION FUNCTION

Subroutine: BINOPD

Description

Evaluates the probability of both obtaining a specified number of successes and of


obtaining from zero to the specified number of successes in a binomial trial.

Method

If X is a binomial random variable then


Px(X=t)= (~)ptqn-t t=O, 1,2 ... n
= 0 otherwise
where n is the number of trials, p the probability of a success on a single trial and
q = 1 -po
In the subroutine use is made of the relationships:
Px(X= t)=qn t =0
Px(X= t)= ((n + 1- t)/t) (P/q)px(X= t - 1) t = 1,2 ... n
t
Fx(t) =Px(X~ t) =~ Px(k) t =0,1,2 ... n
k=O

Subroutine Listing

2000 REM BINOMIAL PROBABILITY AND DISTRIBUTION


2010 REM FUNCTION
2020 REM
2030 REM SUBROUTINE: BINOPD
2040 REM
2050 REM EVALUATES P(X=T) AND P(X<=T)
2060 REM FOR A BINOMIAL DISTRIBUTION
2070 REM
2080 REM VARIABLES:
2090 REM INPUT:
2100 REM NB ...... NUMBER OF TRIALS
2110 REM NUMSUC .. NUMBER OF SUCCESSES
2120 REM PB ...... PROB. OF SUCCESS ON A SINGLE TRIAL
2130 REM OUTPUT:
2140 REM FX ...... PROB. OF NUMSUC OR FEWER SUCCESSES
2150 REM PX ...... PROB. OF EXACTLY NUMSUC SUCCESSES
2160 REM LOCAL: ... R, OB
The Subroutines 21

2170 REM
2180 REM CHECK INPUT DATA
2190 IF PB < 0 OR PB > 1 OR NB < 1 THEN GOTO 2310
2200 IF NUMSUC > NB OR NUMSUC < 0 THEN GOTO 2310
2210 LET QB 1 - PB
2220 LET PX = QB~NB
2230 LET FX = PX
2240 IF NUMSUC = 0 THEN GOTO 2290
2250 FOR R = 1 TO NUMSUC
2260 LET PX (NB + 1 - R)*PB*PX/(R*QB)
2270 LET FX = FX + PX
2280 NEXT R
2290 REM
2300 RETURN
2310 REM
2320 PRINT " PB, NB OR NUMSUC INVALID"
2330 PRINT" PB = "; PB; ", NB = "; NB;
2340 PRINT ", NUMSUC = "; NUMSUC
2350 END

Sample Program

If five dice are thrown, determine (a) the probability that exactly three sixes are
thrown and (b) the probability of throwing three or more sixes.
This problem may be tackled conveniently by considering the probability that
(a) exactly two numbers other than six are thrown and (b) that zero, one or two
numbers which are not sixes are thrown. The probability of not throwing a six is
5/6.

1000 REM SAMPLE PROGRAM: PBINOPD


1010 REM
1020 REM CALCULATES THE VALUES OF THE PROBABILITY AND
1030 REM DISTRIBUTION FUNCTIONS FOR A BINOMIAL
1040 REM DISTRIBUTION OF PARAMETERS PB AND NB
1050 REM
1060 REM SET INITIAL VALUES
1070 LET NB = 5
1080 LET PB = 5/6
1090 LET NUMSUC = 2
1100 REM
1110 REM EVALUATE BINOMIAL PROB. AND DIST. FUNCTIONS
1120 REM CALL SUBROUTINE BINOPD
1130 GOSUB 2000
1140 PRINT" P(X) = "; PX, " F(X) "; FX
1150 END

>RUN
P(X) = 3.215E-2 F(X) = 3.5494E-2
Thus (a) the probability of throwing three sixes is 0.032150 and (b) the
probability of throwing three or more sixes is 0.035494.
22 Advanced BASIC Scientific Subroutines

POISSON PROBABILITY AND DISTRIBUTION FUNCTION

Subroutine: POISPD

Description

Computes the probabilities of various events in a Poisson trial. Evaluates the


probability of obtaining an exact number of events, the probability of obtaining
from zero to a specified number of events and the probability of obtaining a
specified number or more events.

Method

If X is a Poisson random variable then


PxeX=t)=eLt/t!)exp(-L) t=O, 1,2 ...
where L is the mean of the distribution.
In the subroutine use is made of the relationships:
Px(X= t) =(L/t)px(X= t - 1) t = 1,2 ...
The distribution function F x(t), the probability of t or fewer events, is given by
t
Fx(t)= ~ Px(X=k) t=O, 1,2 ...
k=O

The probability of t or more events is


t-l
P(X~t) = 1- ~ P(X=k) t= 1,2 ...

°
k=O

=1 t =

Subroutine Listing

2000 REM POISSON PROBABILITY AND


2010 REM DISTRIBUTION FUNCTION
2020 REM
2030 REM SUBROUTINE: POISPD
2040 REM
2050 REM EVALUATES P(X = T), P(X (= T) AND P(X >= T)
2060 REM FOR A POISSON DISTRIBUTION
2070 REM
2080 REM VARIABLES:
2090 REM INPUT:
2100 REM L1 ...... MEAN VALUE
2110 REM NUMEVT .. NUMBER OF EVENTS
2120 REM OUTPUT:
2130 REM FX ...... PROB. OF NUMEVT OR FEWER EVENTS
The Subroutines 23

2140 REM PGTEQX .. PROB. OF NUMEVT OR MORE EVENTS


2150 REM PX ...... PROB. OF EXACTLY NUMEVT EVENTS
2160 REM LOCAL: ... P
2170 REM
2180 REM CHECK INPUT DATA
2190 IF NUMEVT < 0 OR L1 < 0 THEN GO TO 2310
2200 LET PX = EXP(-L1)
2210 LET PGTEQX = 1
2220 LET FX = PX
2230 IF NUMEVT = 0 THEN GOTO 2290
2240 FOR. P = 1 TO NUMEVT
2250 LET PGTEQX = PGTEQX - PX
2260 LET PX L1*PX/P
2270 LET FX = FX + PX
2280 NEXT P
2290 REM
2300 RETURN
2310 REM
2320 PRINT" NUMEVT OR L1 INVALID,"
2330 PRINT" NUMEVT = "; NUMEVT; ", L1 "; L1
2340 END

Sample Program

Telephone calls arrive at a switch board on average at a rate of two per minute.
Assuming that the process can be modelled as a Poisson distribution, determine the
probability of (a) exactly t, (b) at least t and (c) t or fewer calls arriving in a one
minute interval for t = 0, 1,2, 3, 4 and 5 calls.

1000 REM SAMPLE PROGRAM: PPOISPD


1010 REM
1020 REM DETERMINE THE PROBABILITIES P(X = T),
1030 REM P(X < = T) AND P(X >= T) FOR A POISSON
1040 REM DISTRIBUTION FOR N1 AND N2 EVENTS
1050 REM
1060 REM SET INITIAL VALUES
1070 LET L1 2
1080 LET N1 = o
1090 LET N2 = 5
1100 PRINT " T", " P(X = T)", " P(X <= T)";
1110 PRINT" P(X >= T)"
1120 REM
1130 REM COMPUTE POISSON PROBABILITIES FOR EACH EVENT
1140 REM CALL SUBROUTINE POISPD
1150 FOR T = N1 TO N2
1160 LET NUMEVT = T
1170 GOSUB 2000
1180 PRINT T, PX, FX, PGTEQX
1190 NEXT T
1200 END
24 Advanced BASIC Scientific Subroutines

>RUN
T P(X = T) P(X <= T) P(X >= T)
o 0.13534 0.13534 1
1 0.27067 0.40601 0.86466
2 0.27067 0.67668 0.59399
3 0.18045 0.85712 0.32332
4 9.0224E-2 0.94735 0.14288
5 3.6089E-2 0.98344 5.2653E-2

The table displays the required probabilities. It is interesting to compare the


computed probability of 1, 2, 3, 4 or 5 calls arriving in a single minute with the
value of 0.8491 found by simulation (see subroutine RNDPSN). From the results
presented in the table it may be deduced that the theoretical value of
5
l; Px(X=t)
t"'l

is 0.8481. The discrepancy is well within the expected precision of the process
of simulation.
The Subroutines 25

AREA UNDER THE NORMAL CURVE

Subroutine: NORMDT

Description

Computes the area under the upper and lower tails of the standard normal curve.

Method

The integrals

N(z)=(1/21T)t fz" exp(-x2/2)dx and

N(z) = (1/21T)t f~:'Xp(_X2/2)dx


are evaluated using two approximations:
N(z) =0.5 - Zf(Z2) when Iz I:s:;;; 1.28 and
N(z) = (1/21T'fl exp(-z2/2)f(z) when Iz I> 1.28
This technique is based on the work published by Adams (Adams, 1969) and
subsequently adapted and published in Applied Statistics Algorithms (Griffiths
and Hill, 1985a).

Subroutine Listing

2000 REM AREA UNDER THE NORMAL CURVE


2010 REM
2020 REM SUBROUTINE: NORMDT
2030 REM
2040 REM COMPUTES BOTH UPPER AND LOWER TAIL AREAS
2050 REM UNDER THE STANDARD NORMAL N(O,l) CURVE
2060 REM
2070 REM VARIABLES:
2080 REM INPUT:
2090 REM Z ..•.... VALUE OF NORMAL VARIATE
2100 REM OUTPUT:
2110 REM LAREA .•• AREA FROM MINUS INFINITY TO Z
2120 REM UAREA .•• AREA FROM Z TO PLUS INFINITY
2130 REM LOCAL: ••• AZ, FAZ, NORMA, V1
2140 REM
2150 REM SET INITIAL CONDITIONS AND TEST
2160 REM FOR LARGE ABS(Z)
2170 LET AZ = ABS(Z)
2180 LET NORMA = 0
26 Advanced BASIC Scientific Subroutines

2190 IF AZ > 12 GOTO 2400


2200 LET FAZ = 0.5*AZ*AZ
2210 IF AZ <= 1.28 THEN GOTO 2330
2220 REM
2230 REM COMPUTE FOR ABS(Z) > 1.28
2240 LET FAZ = 0.398942280385*EXP(-FAZ)
2250 LET V1 AZ + 3.99019417011
2260 LET V1 AZ + 0.742380924027 + 30.789933034/V1
2270 LET V1 AZ + 4.8385912808 - 15.1508972451/V1
2280 LET V1 AZ - 0.151679116635 + 5.29330324926/V1
2290 LET V1 AZ + 3.98064794E-4 + 1.98615381364/V1
2300 LET V1 1.00000615302/V1
2310 LET NORMA = FAZ/(AZ - 3.8052E-8 + V1)
2320 GO TO 2400
2330 REM
2340 REM COMPUTE FOR ABS(Z) <= 1.28
2350 LET V1 FAZ + 5.92885724438
2360 LET V1 = FAZ + 2.62433121679 + 48.6959930692/V1
2370 LET V1 = FAZ + 5.75885480458 - 29.8213557808/V1
2380 LET V1 = 0.399903438504*FAZ/V1
2390 LET NORMA = 0.5 - AZ*(0.398942280444 - V1)
2400 REM
2410 REM SET LAREA AND UAREA FOR -VE AND +VE Z
2420 IF Z >= 0 THEN GOTO 2460
2430 LAREA = NORMA
2440 UAREA = 1 - NORMA
2450 GOTO 2490
2460 REM Z >= 0
2470 LAREA 1 - NORMA
2480 UAREA = NORMA
2490 REM
2500 RETURN

Sample Program

Determine the area under the lower and upper tails of the standard normal dis-
tribution for values of z in the range - 6 to + 6 atintervals of 0.5

1000 REM SAMPLE PROGRAM: PNORMDT


1010 REM
1020 REM TABULATES AREA UNDER THE NORMAL N(O,l) CURVE
1030 REM
1040 REM VARIABLES:
1050 REM N1 ....... MAXIMUM VALUE OF Z
1060 REM N2 ....... VALUE OF STEP
1070 REM N3 ....... LOWEST VALUE OF Z
1080 REM
1090 REM SET INITIAL VALUES AND PRINT HEADINGS
1100 LET N1 = 6
The Subroutines 27

1110 LET N2 = 0.5


11.20 LET N3 = -6
1130 PRINT " VARIATE", " LOWER", " UPPER"
1140 PRINT " Z", " AREA", " AREA"
1150 REM
1160 REM COMPUTE AREA UNDER NORMAL CURVE
1170 REM CALL SUBROUTINE NORMDT
1180 FOR Z = N3 TO Nl STEP N2
1190 GOSUB 2000
1200 PRINT Z, LAREA, UAREA
1210 NEXT Z
1220 END

>RUN
VARIATE LOWER UPPER
Z AREA AREA
-6 9.86588E-10 1
-5.5 1.89896E-8 1
-5 2.86652E-7 1
-4.5 3.39767E-6 0.999997
-4 3.16712E-5 0.999968
-3.5 2.32629E-4 0.999767
-3 1.3499E-3 0.99865
-2.5 6.20967E-3 0.99379
-2 2.27501E-2 0.97725
-1. 5 6.68072E-2 0.933193
-1 0.158655 0.841345
-0.5 0.308538 0.69l462
0 0.5 0.5
0.5 0.691462 0.308538
1 0.841345 0.158655
1.5 0.933193 6.68072E-2
2 0.97725 2.27501E-2
2.5 0.99379 6.20967E-3
3 0.99865 1.3499E-3
3.5 0.999767 2.32629E-4
4 0.999968 3.16712E-5
4.5 0.999997 3.39767E-6
5 1 2.86652E-7
5.5 1 1.89896E-8
6 1 9.86588E-10

The results agree with those published in five-figure tables - much higher
accuracies are claimed for this method.

Notes

1. The test AZ > 12 may be adjusted to take account of precision of the working
and the magnitude of the smallest number the machine can hold. This facility
28 Advanced BASIC Scientific Subroutines

will prove useful if unusually large values of z are likely to occur by design or in
error and interruption of the program in run time proves undesirable.
2. For full accuracy it is important that the tail area selected for study is com-
puted directly; that is, if z > 0, use UAREA to compute the small area and not
1 - LAREA. Similarly, if z < 0 use LAREA in preference to 1 - UAREA.
The Subroutines 29

EXPONENTIAL DENSITY AND DISTRIBUTION FUNCTIONS

Subroutine:~lVDD

Description

Computes values of the density and distribution functions for an exponential


distribution.

Method

Density function

Ix(t) =L.exp(-Lt) t >0


Ix(t) =0 otherwise
Distribution function
Fx(t) = I - exp(-Lt) t ~ 0
F x(t) =0 otherwise
The mean value of the exponential distribution is IlL.

Subroutine Listing

2000 REM EXPONENTIAL DENSITY AND DISTRIBUTION


2010 REM FUNCTIONS
2020 REM
2030 REM SUBROUTINE: XPONDD
2040 REM
2050 REM EVALUATES DENSITY F(X = T) AND DISTRIBUTION
2060 REM P(X <= T) FOR AN EXPONENTIAL DISTRIBUTION
2070 REM OF PARAMETER L1
2080 REM
2090 REM VARIABLES:
2100 REM INPUT:
2110 REM L1 •.•••• WHERE 1/L IS THE MEAN EVENT TIME
2120 REM T1 .•••.• TIME TO FIRST EVENT
2130 REM OUTPUT:
2140 REM DFX ••••• VALUE OF DENSITY FUNCTION, FX(X=T)
2150 REM FX .••..• VALUE OF DIST. FUNCTION, P(X<=T)
2160 REM LOCAL: ••• VEXPLX
2170 REM
2180 REM CHECK VALIDITY OF L1 AND T1
2190 IF L1 < 0 OR T1 < 0 THEN GOTO 2260
2200 REM
2210 REM COMPUTE VALUES OF DFX AND FX
2220 LET VEXPLX = EXP(-L1*Tl)
2230 LET DFX = L1*VEXPLX
30 Advanced BASIC Scientific Subroutines

2240 LET FX = 1 - VEXPLX


2250 RETURN
2260 REM
2270 PRINT" L1 OR T1 INVALID.".
2280 PRINT II L1 = ". L1. ". T1 = "; T1
2290 END

Somple Program

The mean life of a gas discharge tube under certain conditions is 92 hours
(IlL = 92). Use the exponential distribution to determine the density at L = 1/92
and the probability that the component will fail during the fIrst 50 hours of
operation.

1000 REM SAMPLE PROGRAM: PXPONDD


1010 REM
1020 REM EVALUATES THE DENSITY AND PROBABILITY THAT
1030 REM IT IS LESS THAN TIME T1 TO THE FIRST
1040 REM FAILURE IN AN EXPONENTIAL DISTRIBUTION
1050 REM
1060 LET L1 = 1/92
1070 LET T1 = 50
1080 REM
1090 REM DETERMINE DENSITY AT T1 AND AREA UNDER CURVE
1100 REM CALL SUBROUTINE XPONDD
1110 GOSUB 2000
1120 PRINT II TIME = "; T1. ". MEAN = ". L1
1130 PRINT II DENSITY = ". DFX
1140 PRINT" AREA UNDER CURVE ". FX
1150 END

>RUN
TIME = 50. MEAN = 1.087E-2
DENSITY = 6.312E-3
AREA UNDER CURVE = 0.4193

The probability that the tube will fail in less than 50 hours is 0.4193; the
density of the probability function at this time is 0.006312.
The Subroutines 31

NATURAL LOGARITHM OF THE COMPLETE GAMMA FUNCTION

Subroutine: LlVGAAfAf

Description

Evaluates the natural logarithm of the complete gamma function rea) for a > O.

Afethod

rea) LOOtO:-1exp(-t)dt
Integration by parts yields
rea + 1) = area) a> 0
In the computation use is made of the relationship:

rea) = rea + 5)
a(a + 1)(a + 2)(a + 3)(a + 4)

r(a + 5) is solved to sufficient accuracy with the aid of Stirling's approximation


(Iyanaya and Kawada, 1980) in the form
10
In(r(x)) = (x - 0.5)ln(x) - x + O.5ln(27T) + ~
n=l
(l)n-l B
-
2n(2n - 1)x
:n_
n
1

where B 2n are the Bernoulli numbers.

Subroutine Listing

2000 REM NATURAL LOGARITHM OF GAMMA FUNCTION


2010 REM
2020 REM SUBROUTINE: LNGAMM
2030 REM
2040 REM EVALUATES THE NATURAL LOGARITHM OF THE GAMMA
2050 REM FUNCTION FOR PARAMETER ALPHA FOR ALPHA> O.
2060 REM RPI IS SET EQUAL TO PI
2070 REM
2080 REM VARIABLES:
2090 REM INPUT:
2100 REM ALPHA ..• GAMMA PARAMETER
2110 REM OUTPUT:
2120 REM NLGGAM .. NATURAL LOGARITHM OF GAMMA(ALPHA)
2130 REM LOCAL: ... A1, AS, C1, C2, C3, C4, C5, RPI
2140 REM V1, V2
2150 REM
2160 REM SET INITIAL CONDITIONS AND CHECK
2170 REM VALIDITY OF ALPHA
32 Advanced BASIC Scientific Subroutines

2180 IF ALPHA (= 0 OR ALPHA > 1E7 THEN GOTO 2360


2190 LET C1 = 1/12
2200 LET C2 = -1/360
2210 LET C3 = 1/1260
2220 LET C4 = -1/1680
2230 LET C5 = 5/5940
2240 LET RPI = 3.1415926536
2250 REM
2260 REM COMPUTE NLGGAM
2270 LET A1 ALPHA
2280 LET V1 = A1*(A1 + 1)*(A1 + 2)*(Al + 3)*(A1 + 4)
2290 LET V1 LN(V1)
2300 LET AS ALPHA + S
2310 LET V2 l/(AS*AS)
2320 LET V2 V2*(C2 + V2*(C3 + V2*(C4 + CS*V2»)
2330 LET NLGGAM (C1 + V2)/A5 - AS + 0.5*LN(2*RPI)
2340 LET NLGGAM = (AS - O.S)*LN(AS) + NLGGAM - V1
2350 RETURN
2360 REM
2370 PRINT" ALPHA INVALID, ALPHA = "; ALPHA
2380 END

Sample Program

Use the subroutine LNGAMM to evaluate In(r(a» for a = 0.1, 0.3,1,1.32,2,


2.5,3,10,300.62.

1000 REM SAMPLE PROGRAM: PLNGAMM


1010 REM
1020 REM EVALUATES THE NATURAL LOGARITHM OF THE GAMMA
1030 REM FUNCTION FOR SEVERAL VALUES OF ALPHA
1040 REM
1050 DATA 0.1, 0.3, 1, 1.32, 2, 2.S, 3, 10, 300.62
1060 PRINT" ALPHA ";" LN(T(ALPHA»"
1070 REM
1080 REM CALL SUBROUTINE LNGAMM FOR EACH DATA VALUE
1090 FOR J = 1 TO 9
1100 READ ALPHA
1110 GOSUB 2000
1120 PRINT ALPHA, NLGGAM
1130 NEXT J
1140 END

>RUN
ALPHA LN(T(ALPHA) )
0.1 2.2S27
0.3 1.0958
1 o
1. 32 -0.11133
2 1.8626E-9
2.5 0.28468
The Subroutines 33

3 0.69315
10 12.802
300.62 1412.7

These results agree with those published in tables (Pearson, 1965).

Notes

1. The result will be accurate to at least 9 decimal digits given that the computer
is capable of such accuracy.
2. High values of ALPHA have the potential to cause overflow. The program is
interrupted if ALPHA is greater than lE7. This limiting value may be adjusted
to suit the capacity of the reader's machine.
34 Advanced BASIC Scientific Subroutines

RATIO OF THE INCOMPLETE GAMMA FUNCTION

Subroutine: GAMMFN

Description

Evaluates the ratio of the incomplete gamma function G (p, y) to the complete
function r(p) for p > 0, y > 0.
Requires subroutine LNGAMM.

Method

f:
The ratio is defined by

G(y,p) = (Ijr(p)) tP-1exp(-t)dt p>O,y>O

The algorithm used to evaluate G(y,p) has been published by Lau (Griffiths
and Hill, I985b) and exploits the relationship

G(y,p) = (yPexp(-y))jr(p + 1)) i


n=O
Cn(y,p)

where

Co(y,p) = 1 when n =0 and


Cn(y,p) = (y/(P + n))Cn - 1 (y,p) for n:::: 1,2 ...

Subroutine Listing

3000 REM INCOMPLETE GAMMA FUNCTION RATIO


3010 REM
3020 REM SUBROUTINE: GAMMFN
3030 REM
3040 REM COMPUTES THE INCOMPLETE GAMMA FUNCTION RATIO
3050 REM DEFINED AS THE PRODUCT OF 1/GAMMA(P) AND THE
3060 REM INTEGRAL (T~(P - l»EXP(-T).DT BETWEEN
3070 REM T = 0 AND T = Y WHERE P > 0 AND Y > O.
3080 REM REQUIRES SUBROUTINE LNGAMM.
3090 REM
3100 REM VARIABLES:
3110 REM INPUT:
3120 REM NLGGAM .• FROM SUBROUTINE LNGAMM
3130 REM PARG .... PARAMETER P
3140 REM YARG .... PARAMETER Y
3150 REM OUTPUT:
3160 REM GRAT .... INCOMPLETE GAMMA FUNCTION RATIO
3170 REM LOCAL: ... DERROR, K1, PSUM, TERM
3180 REM
The Subroutines 35

3190 REM CHECK VALIDITY OF INPUT


3200 IF PARG <= 0 OR YARG <= 0 THEN GOTO 3480
3210 REM
3220 REM CALL LNGAMM AND EVALUATE GAMMA(PARG + 1)
3230 LET ALPHA = PARG + 1
3240 GOSUB 2000
3250 REM
3260 REM EVALUATION OF CONSTANT TERM
3270 LET K1 = EXP(PARG*LN(YARG) - NLGGAM - YARG)
3280 IF K1 = 0 THEN GOTO 3400
3290 REM
3300 REM SUM SERIES FOR REQUIRED PRECISION
3310 LET GRAT = 1
3320 LET DERROR = 1E-6
3330 LET TERM = 1
3340 LET PSUM = PARG
3350 IF TERM < GRAT*DERROR THEN GOTO 3440
3360 LET PSUM PSUM + 1
3370 LET TERM TERM*YARG/PSUM
3380 LET GRAT = GRAT + TERM
3390 GOTO 3350
3400 REM
3410 PRINT " YARG AND PARG OUT OF RANGE, GRAT SET";
3420 PRINT " TO ZERO"
3430 PRINT" PARG = "; PARG; ", YARG = "; YARG
3440 REM
3450 LET GRAT = GRAT*K1
3460 RETURN
3470 REM
3480 PRINT " PARG OR YARG INVALID"
3490 PRINT" PARG = "; PARG; ", YARG "; YARG
3500 END

Sample Program

Determine the value for G(y,p) for the following values ofp andy:
p 0.5 0.5 5.5 13 26 35 35
y 7.85E-5 5.4135 3.4945 14.623 32.711 22.721 56.1585

1000 REM SAMPLE PROGRAM: PGAMMFN


1010 REM
1020 REM EVALUATES THE INCOMPLETE GAMMA FUNCTION
1030 REM RATIO G(Y,P) FOR N1 VALUES OF Y AND P
1040 DATA 0.5, 7.85E-5, .5, 5.4135, 5.5, 3.4945, 13
1050 DATA 14.623, 26, 32.711, 35, 22.721, 35, 56.1585
1060 REM
1070 REM SET INITIAL VALUES AND PRINT HEADINGS
1080 LET N1 = 7
1090 PRINT" P", " Y", " G(Y,P)"
1100 REM
1110 REM EVALUATE GAMMA FUNCTION
36 Advanced BASIC Scientific Subroutines

1120 REM CALL GAMMFN FOR EACH SET OF DATA VALUES


1130 FOR I = 1 TO N1
1140 READ P, Y
1150 LET PARG = P
1160 LET YARG = Y
1170 GOSUB 3000
l1S0 PRINT P, Y, GRAT
1190 NEXT I
1200 END

>RUN
P Y G(Y,Pl
0.5 7.S5E-5 9.9972E-3
0.5 5.4135 0.999
5.5 3.4945 0.20003
13 14.623 0.69999
26 32.711 0.S9999
35 22.721 1. 0001E-2
35 56.159 0.999

These results may be checked against the tables for X2 by substituting degrees
of freedom = p /2 and X2 = Y/2 or directly against tables for the incomplete gamma
function (Pearson, 1956).

Notes

1. Accuracy is set by the value of DERROR. It should be borne in mind when


determining the required precision that rounding errors will accumulate during
the summation of the series. IE - 6 for DERROR is a reasonable choice for
machines working to eight significant figures.
2. At the extremes of the distribution, local variable Kl will be zero. In this case
execution is not terminated though a warning is printed indicating that the value
returned for GRAT is not correct. The major use for this subroutine is likely to
be in significance testing and in this application it is unlikely that extreme values
for GRAT will be required.
The Subroutines 37

RATIO OF THE INCOMPLETE BETA FUNCTION

Subroutine: BETAFN

Description

Evaluates the ratio of the incomplete beta function Ix(P, q) to the complete func-
tion B(p, q) for p > 0, q > 0, 0 < x < 1. The natural logarithm of the complete
beta function, In B(p, q), is also determined.
Requires subroutine LNGAMM.

Method

The ratio is defmed

Ix(p, q) = (I/B(P, q)) f: t p - 1 (1 - t)q -1 dt (1)

where
B(p, q) = (r(p)r(q»/r(p + q)
The subroutine described in this section is adapted from that published in
FORTRAN by Majumder and Bhattacharjee (Griffiths and Hill, 1985c).
Ix(P, q) in (1) is integrated by parts. Ifp ~ (p + q)x, the resulting series

I (p q) = r(p + q)xP(1 - X)q-1 + I (p + 1 q _ 1) (2)


x , rep + 1) rep) x ,
is evaluated up to s times where
s = INT(q + (1 -x) (p + q» (3)
The process is continued if necessary with the aid of the recurrence relation:
rep + q)xP+S(1 x)q-s
Ix(p+s,q-s)=: - +Ix(p+s+l,q-s) (4)
r(p + s + 1) r(q - s)
If (3) does not produce a positive integer then only equation (4) is employed.
The ratio between terms is determined with the aid of rea + 1) = area) and is used
to facilitate summation. The process is terminated when the required accuracy is
achieved.
If p < (p + q)x then Ix -1 (q, p) is found by the above method and the equation
Ix(p,q) = l-Ix_1 (q,p)
used to determine Ix(P, q).
Ln B(p, q) is evaluated with the help of subroutine LNGAMM which determines
In r (a) for a > 1.
38 Advanced BASIC Scientific Subroutines

Subroutine Listing

3000 REM INCOMPLETE BETA FUNCTION RATIO


3010 REM
3020 REM SUBROUTINE: BETAFN
3030 REM
3040 REM COMPUTES THE INCOMPLETE BETA FUNCTION RATIO
3050 REM DEFINED AS THE PRODUCT OF 1/B(P,Q) AND
3060 REM INTEGRAL (T A(P-1»(1-T)A(Q-1).DT
3070 REM BETWEEN T = 0 AND T = X, WHERE P>=O,
3080 REM Q>=O, O<=X<=l. ALSO COMPUTES LN(B(P,Q».
3090 REM REQUIRES SUBROUTINE LNGAMM
3100 REM
3110 REM VARIABLES:
3120 REM INPUT:
3130 REM NLGGAM .. FROM SUBROUTINE LNGAMM
3140 REM PARG .... PARAMETER P
3150 REM QARG .... PARAMETER Q
3160 REM XBET .... UPPER LIMIT OF INTEGRATION, X
3170 REM OUTPUT:
3180 REM BRAT .... INCOMPLETE BETA FUNCTION RATIO
3190 REM NLGBET .. NATURAL LOG OF COMPLETE BETA
3200 REM FUNCTION, B(P,Q)
3210 REM LOCAL: ... BER, BLE, CB1, CX, PQSUM, PARG1,
3220 REM QARG1, RATX, TERM, VB1, VS, XBET1
3230 REM
3240 REM CHECK INPUT AND SET INITIAL VALUES
3250 LET BRAT = XBET
3260 IF PARG <= 0 OR QARG <= 0 THEN GOTO 3940
3270 IF XBET > 1 OR XBET < 0 THEN GOTO 3940
3280 LET PQSUM = PARG + QARG
3290 LET BER = 1E-7
3300 LET CX = 1 - XBET
3310 REM
3320 REM COMPUTE LOG OF COMPLETE BETA FUNCTION
3330 REM CALLS SUBROUTINE LNGAMM
3340 LET ALPHA = PARG
3350 GOSUB 2000
3360 NLGBET = NLGGAM
3370 LET ALPHA = QARG
3380 GOSUB 2000
3390 LET NLGBET = NLGGAM + NLGBET
3400 LET ALPHA = PQSUM
3410 GOSUB 2000
3420 LET NLGBET = NLGBET - NLGGAM
3430 IF XBET = 0 OR XBET 1 THEN GOTO 3910
3440 REM
3450 REM CHECK (P + Q)X AND ADJUST ARGUMENTS
3460 IF PARG >= PQSUM*XBET THEN GOTO 3550
3470 REM
3480 REM COMPUTATION FOR P < (P+Q)X
3490 LET XBET1 = CX
3500 LET CX = XBET
3510 LET PARG1 = QARG
The Subroutines 39

3520 LET QARG1 PARG


3530 LET BLE = 0
3540 GOTO 3610
3550 REM
3560 REM COMPUTATION FOR P )= (P + Q)*X
3570 LET XBET1 XBET
3580 LET PARG1 PARG
3590 LET QARG1 QARG
3600 LET BLE = 1
3610 REM
3620 REM SET INITIAL VALUES FOR SERIES SUMMATION
3630 LET TERM = 1
3640 LET CB1 = 1
3650 LET BRAT = 1
3660 LET VS = INT(QARG1 + CX*PQSUM)
3670 REM
3680 REM SUM SERIES
3690 LET RATX = XBET1/CX
3700 REM
3710 LET VB1 QARG1 - CB1
3720 IF VS = 0 THEN LET RATX = XBET1
3730 REM
3740 LET TERM = TERM*VBl*RATX/(PARGl + CBl)
3750 LET BRAT = BRAT + TERM
3760 LET VBl = ABS(TERM)
3770 REM
3780 REM CHECK PRECISION OF SUMMATION
3790 IF VBl <= BER AND VBl <= BER*BRAT THEN GOTO 3860
3800 LET CBl = CBl + 1
3810 LET VS = VS - 1
3820 IF VS )= 0 THEN GOTO 3700
3830 VB1 = PQSUM
3840 LET PQSUM = PQSUM + 1
3850 GOTO 3730
3860 REM
3870 REM COMPUTE FINAL RESULT
3880 LET VBl = PARG1*LN(XBET1) + (QARGl - l)*LN(CX)
3890 LET BRAT BRAT*EXP(VBl - NLGBET)/PARGl
3900 IF BLE = 0 THEN LET BRAT = 1 - BRAT
3910 REM
3920 RETURN
3930 REM
3940 PRINT II INPUT DATA OUT OF RANGE, PARG = "; PARG
3950 PRINT" QARG = "; QARG; ", XBET = "; XBET
3960 END

Sample Program

Determine the incomplete beta ratio I X(p, q) for the values of p, q and x given
in the table overleaf. Also evaluate the complete beta function, B(p, q), for each
pair of values of p and q.
40 Advanced BASIC Scientific Subroutines

p q x

0.5 0.5 6.158E - 3


0.5 500 1.579E - 5
1 0.5 0.3597
1 500 4.462E - 4
2.5 2 0.41
2.5 12 6.13E- 2
4.5 2 0.79
5 1.5 0.3373
15 3 0.7163
60 500 0.5172
500 0.5 0.9984

1000 REM SAMPLE PROGRAM: PBETAFN


1010 REM
1020 REM COMPUTES THE AREA UNDER THE INCOMPLETE BETA
1030 REM RATIO IXB(P,Q) AND EVALUATES THE COMPLETE
1040 REM BETA FUNCTION FOR N1 SETS OF P, Q AND X
1050 REM
1060 DATA 0.5, 0.5, 6.158E-3, 0.5, 500, 1.579E-5
1070 DATA 1, 0.5, 0.3597
1080 DATA 1, 500, 4.4623E-4, 2.5, 2, 0.41
1090 DATA 2.5, 12, 6.13E-2, 4.5, 2, 0.79
1100 DATA 5.0, 1.5, 0.3373, 15, 3, 0.7163
1110 DATA 60, 500, 0.5172, 500, 0.5, 0.9984
1120 REM
1130 REM SET INITIAL VALUES AND PRINT HEADING
1140 LET N1 = 11
1150 PRINT " P", " a", " X ; ..
1160 PRINT" IX(B(P,Q»"," B(P,Q) "
1170 REM
1180 REM CALL SUBROUTINE BETAFN FOR EACH SET OF DATA
1190 FOR I = 1 TO N1
1200 READ P, Q, X
1210 LET PARG = P
1220 LET aARG = a
1230 LET XBET = X
1240 GOSUB 3000
1250 PRINT P, Q, X, BRAT, EXP(NLGBET)
1260 NEXT I
1270 END

>RUN
P Q X IX(B(P,Q» B(P,Q)
0.5 0.5 6.158E-3 5.001E-2 3.142
0.5 500 1.579E-5 9.997E-2 7.929E-2
1 0.5 0.3597 0.1998 2
1 500 4.462E-4 0.2 2E-3
The Subroutines 41

2.5 2 0.41 0.2664 0.1143


2.5 12 6.13E-2 0.1 2.298E-3
4.5 2 0.79 0.6734 4.04E-2
5 1.5 0.3373 1. 002E-2 7.388E-2
15 3 0.7163 0.1 4.902E-4
60 500 0.5172 1 0
500 0.5 0.9984 0.2058 7.929E-2

These results agree with those published in tables (Pearson, 1968).

Notes

1. Accuracy is controlled by BER.


2. B(p, q) is most readily determined by setting x = 1 and solving EXP(NLGBET).
42 Advanced BASIC Scientific Subroutines

cm-SQUARED DISTRIBUTION

Subroutine: CmSQD

Description

Computes the area under the X2 curve from zero to a positive argument as a
function of the number of degrees of freedom.
Requires subroutines LNGAMM and GAMMFN.

Method

The distribution function for chi-squared is

Fx(x) = (1/(2 m/2 rctm))) f: u(m-2)/2 exp(-u/2) du x;;;;t 0

F x(x) = 0 x <0 m = 1, 2 ...


where m is the number of degrees of freedom.
This may be treated as a special case of the incomplete gamma distribution:

G(y,p) =(l/r(p)) f: tp-1exp(-t) dt p > O,y > 0


in which 2p = m and 2y = x.
The subroutine employs this relationship to evaluate F x(x).

Subroutine Listing

4000 REM CHI-SQUARED DISTRIBUTION FUNCTION


4010 REM
4020 REM SUBROUTINE: CHISQD
4030 REM
4040 REM COMPUTES AREA UNDER CHI-SQUARED DISTRIBUTION
4050 REM FOR OF DEGREES OF FREEDOM FROM ZERO TO XCHI
4060 REM REQUIRES SUBROUTINES GAMMFN AND LNGAMM
4070 REM
4080 REM VARIABLES:
4090 REM INPUT:
4100 REM DF ...... DEGREES OF FREEDOM
4110 REM GRAT .... FROM SUBROUTINE GAMMFN
4120 REM XCHI_ ... VALUE OF ARGUMENT
4130 REM OUTPUT:
4140 REM CHIX2 ... AREA FROM ZERO TO XCHI
4150 REM
4160 REM CHECK OF AND XCHI AND SET INITIAL CONDITIONS
4170 IF OF < 1 OR INT(DF) < DF THEN GO TO 4300
4180 IF XCHI < 0 THEN GOTO 4300
4190 LET CHIX2 = 0
The Subroutines 43

4200 IF XCHI = 0 THEN GOTO 4280


4210 LET PARG 0.5*DF
4220 LET YARG 0.5*XCHI
4230 REM
4240 REM EVALUATE INCOMPLETE GAMMA RATIO
4250 REM CALL GAMMFN
4260 GOSUB 3000
4270 LET CHIX2 = GRAT
4280 REM
4290 RETURN
4300 REM
4310 PRINT " OF OR XCHI INVALID, OF "; OF;
4320 PRINT ", XCHI "; XCHI
4330 END

Sample Program

Evaluate the major and tail areas under the X2 curve for the following values of
argument,x and degrees of freedom, m: 3.93 x 10-3 , 1; 2.706,1; 0.872,6; 5.348,
6; 15.352, 19; 49.513, 38; 46.244, 68; 94.037,68.

1000 REM SAMPLE PROGRAM: PCHISQD


1010 REM
1020 REM CALCULATE THE AREA UNDER THE CHI-SQUARED
1030 REM CURVE FOR N1 VALUES OF DF AND XCHI
1040 REM
1050 DATA 3.93E-3, 1, 2.706, L 0.872, 6, 5.348,6
1060 DATA 15.352, 19, 49.513, 38, 46.244, 68
1070 DATA 94.037, 68
1080 PRINT" D.F.", " XCHI"," CHIX2";
1090 PRINT" 1-CHIX2"
1100 LET N1 = 8
1110 REM
1120 REM CALL CHISQD FOR EACH SET OF DATA VALUES
1130 FOR I = 1 TO N1
1140 READ XCHI, OF
1150 GOSUB 4000
1160 PRINT OF, XCHI, CHIX2, 1-CHIX2
1170 NEXT I
1180 END

>RUN
D.F. XCHI CHIX2 1-CHIX2
1 3.93E-3 5E-2 0.95
1 2.71 0.9 0.1
6 0.872 1E-2 0.99
6 5.35 0.5 0.5
19 15.4 0.3 0.7
38 49 _,5 0.9 0.1
68 46.2 2E-2 0.98
68 94 0.98 2E-2
44 Advanced BASIC Scientific Subroutines

These results agree with those published in statistical tables for x: .


Note

See the section on GAMMFN for comments on precision and magnitude of m


andx.
The Subroutines 45

UPPER TAIL AREA OF THE F-DISTRIBUTION

Subroutine: FDISTR

Description

Computes the area under the upper tail of the F-distribution for (m, n) degrees
of freedom.
Requires subroutines BETAFN and LNGAMM.

Method

The integral of the upper area of the F-distribution, 1 - F(z), is solved with the
aid of the subroutine for the incomplete beta function BETAFN. 1 - F(z) is equal
to I x(P, q) if n/2 is substituted for p, m/2 for q, and n/(n + mz) for x.

Subroutine Listing

4000 REM AREA UNDER THE F-DISTRIBUTION


4010 REM
4020 REM SUBROUTINE: FDISTR
4030 REM
4040 REM COMPUTES THE UPPER-TAIL AREA OF THE
4050 REM F-DISTRIBUTION FOR (DF1,DF2) DEGREES OF
4060 REM FREEDOM (OF) FROM XF TO INFINITY. OF1 IS THE
4070 REM GREATER MEAN SQUARE IN SIGNIFICANCE TESTING.
4080 REM REQUIRES SUBROUTINES BETAFN AND LNGAMM
4090 REM
4100 REM VARIABLES:
4110 REM INPUT:
4120 REM BRAT_ .... OUTPUT FROM BETAFN
4130 REM DF1 ...... OF, GREATER MEAN SQUARE
4140 REM OF2 ...... OF, LESSER MEAN SQUARE
4150 REM XF ....... VALUE OF ARGUMENT
4160 REM OUTPUT:
4170 REM FAREA .... AREA FROM XF TO INFINITY
4180 REM PARG ..... INPUT FOR BETAFN
4190 REM QARG ..... INPUT FOR BETAFN
4200 REM XBET ..... INPUT FOR BETAFN
4210 REM
4220 REM CHECK DATA AND TRANSFORM INPUT FOR BETAFN
4230 IF DF1 < 1 OR DF2 < 1 OR XF < 0 THEN GOTO 4350
4240 IF INT(DF1) < DF1 THEN GOTO 4350
4250 IF INT(DF2) < DF2 THEN GOTO 4350
4260 LET PARG DF2/2
4270 LET QARG = DF1/2
4280 LET XBET = DF2/(DF2 + DF1*XF)
4290 REM
4300 REM COMPUTE BETA RATIO AND FAREA
4310 REM CALL SUBROUTINE BETAFN
4320 GOSUB 3000
46 Advanced BASIC Scientific Subroutines

4330 LET FAREA = BRAT


4340 RETURN
4350 REM
4360 PRINT " DF1. DF2 OR XF INVALID. DF1 "; DF1
4370 PRINT" DF2 = "; DF2; ". XF = "; XF
4380 END

Sample Program

Use the F-distribution to determine the probability of obtaining values for the
F-ratio, si /s~, greater than those shown in the table. m and n are the number of
degrees of freedom corresponding to s1 and s~ respectively.

sVs~ 39.86 5.31 2.69 3.84 2.47 5982 49.0 14.8


m 1 5 4 24 24 8 8 8
n 1 3 30 6 30 1 4 4

1000 REM SAMPLE PROGRAM: PFDISTR


1010 REM
1020 REM COMPUTES THE UPPER-TAIL AREA OF THE
1030 REM F-DISTRIBUTION FOR N1 SETS OF DATA
1040 REM
1050 DATA 1. 1. 39.86. 5. 3. 5.31. 4. 30. 2.69
1060 DATA 24. 6. 3.84. 24. 30. 2.47. 8. 1. 5982
1070 DATA 8. 4. 49.0. 8. 4. 14.8
1080 REM
1090 REM PRINT HEADINGS. READ DATA. COMPUTE FAREA
1100 REM CALL SUBROUTINE FDISTR FOR EACH SET OF DATA
1110 PRINT" D1o'l". " DF2"." XF";
1120 PRINT " FAREA"
1130 LET N1 = 8
1140 FOR I = 1 TO N1
1150 READ DF1. DF2. XF
1160 GOSUB 4000
1170 PRINT DF1. DF2. XF. FAREA
1180 NEXT I
1190 END

>RUN
DF1 DF2 XF FAREA
1 1 39.9 0.1
5 3 5.31 0.1
4 30 2.69 5E-2
24 6 3.84 5E-2
24 30 2.47 9.97E-3
8 1 5.98E3 1E-2
8 4 49 1E-3
8 4 14.8 1E-2

The results agree with those published in tables of the upper percentage points
of the F-distribution.
The Subroutines 47

UPPER TAIL OF STUDENT'S T DISTRIBUTION

Subroutine: TDISTR

Description

Computes the area under the upper tail of Student's central t distribution for n
degrees of freedom.
Requires subroutines BETAFN and LNGAMM.

Method

Use is made of the relationship (t0l./2,n)2 = FOI.,l, n where tOl./2,n denotes the value
of a variable with a t distribution and n degrees of freedom at the point a12. al2 is the
probability that the variable exceeds ta/2 ,no Fa, l,n is similarly defined for the
F-distribution for 1 and n degrees of freedom.
The upper tail probability for t is determined directly from the subroutine
BETAFN rather than via the subroutine FDISTN and is set equal tolx (P,q)/2
(see notes on BETAFN). Ix(P, q) is evaluated by substituting nl2 for p, 0.5 for q,
and nj(n + (t0l.,2)2/2) for X.

Subroutine Listing

4000 REM AREA UNDER STUDENT'S T DISTRIBUTION


4010 REM
4020 REM SUBROUTINE: TDISTR
4030 REM
4040 REM COMPUTES THE AREA UNDER THE UPPER TAIL OF
4050 REM CENTRAL T-DISTRIBUTION FOR OF DEGREES OF
4060 REM FREEDOM FROM XT TO INFINITY.
4070 REM REQUIRES SUBROUTINES BETAFN AND LNGAMM
4080 REM
4090 REM VARIABLES:
4100 REM INPUT:
4110 REM BRAT ..... OUTPUT FROM BETAFN
4120 REM DF ....... DEGREES OF FREEDOM
4130 REM XT ....... VALUE OF ARGUMENT
4140 REM OUTPUT:
4150 REM TAREA .... AREA FROM XT TO INFINITY
4160 REM PARG ..... INPUT FOR BETAlo'N
4170 REM QARG ..... INPUT FOR BETAFN
4180 REM XBET ..... INPUT FOR BETAFN
4190 REM
4200 REM CHECK DATA AND TRANSFORM INPUT FOR BETAFN
4210 IF OF < 1 OR INT(DF) < OF THEN GOTO 4320
4220 IF XT < 0 THEN GOTO 4320
4230 LET PARG DF/2
4240 LET QARG 0_5
4250 LET XBET = DF/(DF + XT*XT)
4260 REM
48 Advanced BASIC Scientific Subroutines

4270 REM COMPUTE BETA RATIO AND TAREA


4280 REM CALL SUBROUTINE BETAFN
4290 GOSUB 3000
4300 LET TAREA = BRAT/2
4310 RETURN
4320 REM
4330 PRINT " DF OR XT INVALID"
4340 PRINT" DF = "; DF; ", XT "; XT
4350 END

Sample Program

Use the subroutine TDISTR to determine the upper tail area of the t distribution
at the following points:
t o 12.706 0.7 2.947
n 1 1 1 10 15
t 0.854 2.704 0.677 1.658
n 30 40 120 120

1000 REM SAMPLE PROGRAM: PTDISTR


1010 REM
1020 REM COMPUTES THE UPPER TAIL AREA OF STUDENT'S
1030 REM CENTRAL T DISTRIBUTION FOR N1 SETS OF DATA
1040 REM
1050 DATA 1, 0, 1, 1, 1, 12.706, 10, 0.7, 15, 2.947
1060 DATA 30, 0.854, 40, 2.704, 120, 0.677, 120, 1.658
1070 REM
1080 REM PRINT HEADINGS, READ DATA, COMPUTE TAREA
1090 REM CALL SUBROUTINE TDISTR FOR EACH ·SET OF DATA
1100 PRINT " OF", " XT", " TAREA"
1110 LET N1 = 9
1i20 FOR I = 1 TO N1
1130 READ DF, XT
1140 GOSUB 4000
1150 PRINT OF, XT, TAREA
1160 NEXT I
1170 END

>RUN
OF XT TAREA
1 0 0.5
1 1 0.25
1 12.706 2.5E-2
10 0.7 0.24994
15 2.947 4.9971E-3
30 0.854 0.19994
40 2.704 5.0058E-3
The Subroutines 49

120 0.677 0.24985


120 1.658 4.9965E-2

These results may be checked against published tables of the t distribution.

Note

For large values ofn (say exceeding 1000) computation time could be considered
too long. It may be helpful to use the normal approximation for large n or set n
= 1000 for n > 1000 with some small loss of accuracy.
50 Advanced BASIC Scientific Subroutines

2.3 General Statistics


MEAN AND VARIANCE

Subroutine: MNVRNC

Description

Computes mean, variance, standard deviation, l:x and l;x2 for a set of data
values. The cases of known and estimated mean values are considered.

Method

The following defInitions are used in the calculations performed by this subroutine:
n = number of data elements in the sample
xi = value of the ith element
x = estimate of population mean
IJ =true population mean.

Description Variable Definition


Sum of elements SUM I l:Xj
Sum of squares of elements SUM2 l:x~
Mean value of elements MEAN
Variance, mean known to
equal sample mean VRMK
Variance, mean estimated
from sample VRME l:(Xj _x)2/(n - 1)
Standard deviation, mean known SDMK V(l:(Xj -1J)2/n)
Standard deviation,
mean estimated SDME

Subroutine Listing

2000 REM MEAN AND VARIANCE


2010 REM
2020 REM SUBROUTINE: MNVRNC
2030 REM
2040 REM COMPUTES MEAN, VARIANCE AND STANDARD
2050 REM DEVIATION FOR KNOWN AND ESTIMATED VALUES
2060 REM OF MEAN. ALSO COMPUTES SUM AND SUM OF
2070 REM SQUARES OF DATA VALUES
2080 REM
2090 REM VARIABLES:
2100 REM INPUT:
The Subroutines 51

2110 REM A() ..... ARRAY OF INPUT DATA


2120 REM NUMDAT .. SAMPLE SIZE
2130 REM OUTPUT:
2140 REM MEAN ...• MEAN VALUE OF SAMPLE
2150 REM SDME .... STANDARD DEVIATION, MEAN ESTIMATED
2160 REM SDMK ...• STANDARD DEVIATION, MEAN KNOWN
2170 REM SUM1 •..• SUM OF DATA VALUES
2180 REM SUM2 •.•• SUM OF SQUARES OF DATA VALUES
2190 REM VRME •... VARIANCE, MEAN ESTIMATED
2200 REM VRMK •... VARIANCE, MEAN KNOWN
2210 REM LOCAL: ... P
2220 REM ARRAY DIMENSIONS:
2230 REM A() ..... (NUMDAT)
2240 REM
2250 REM CHECK INPUT, SET INITIAL VALUES AND COMPUTE
2260 REM SUM1 AND SUM2
2270 IF NUMDAT < 2 THEN GOTO 2420
2280 LET SUM1 = 0
2290 LET SUM2 = 0
2300 FOR P = 1 TO NUMDAT
2310 LET SUM1 = SUM1 + A(P)
2320 LET SUM2 = SUM2 + A(P)*A(P)
2330 NEXT P
2340 REM
2350 REM FIND MEAN, VARIANCE AND STANDARD DEVIATION
2360 LET MEAN = SUM1/NUMDAT
2370 LET VRMK = (SUM2 - MEAN*SUM1)/NUMDAT
2380 LET VRME = VRMK*NUMDAT/(NUMDAT - 1)
2390 LET SDMK SQR(VRMK)
2400 LET SDME SQR(VRME)
2410 RETURN
2420 REM
2430 PRINT " NUMDAT INVALID, NUMDAT "; NUMDAT
2440 END

Sample Program

Use the subroutine MNVRNC to fmd the mean, variance and other summary
statistical data for the sample values 0.9, 1.3, 1.4, 1.2,0.8, 1.

1000 REM SAMPLE PROGRAM: PMNVRNC


1010 REM
1020 REM COMPUTES SOME SUMMARY STATISTICS
1030 REM
1040 REM ARRAY DIMENSIONS:
1050 DIM A(6)
1060 REM
1070 DATA 0.9, 1.3, 1.4, 1.2, 0.8, 1
1080 LET NUMDAT = 6
1090 REM READ INPUT DATA INTO A()
1100 FOR J = 1 TO NUMDAT
1110 READ A(J)
52 Advanced BASIC Scientific Subroutines

1120 NEXT J
1130 REM
1140 REM COMPUTE SUMMARY STATISTICS
1150 REM CALL SUBROUTINE MNVRNC
1160 GOSUB 2000
1170 PRINT " SUM OF DATA VALUES " ,. SUMl
1180 PRINT " SUM OF SQUARES OF DATA VALUES 11 ; SUM2
1190 PRINT " MEAN "; MEAN
1200 PRINT " VARIANCE, MEAN ESTIMATED " ,. VRME
1210 PRINT " VARIANCE, MEAN KNOWN " ,. VRMK
1220 PRINT" STANDARD DEVIATION, MEAN EST. " ,. SOME
1230 PRINT" STANDARD DEVIATION, MEAN KNOWN " ,. SDMK
1240 END

>RUN
SUM OF DATA VALUES 6.6
SUM OF SQUARES OF DATA VALUES 7.54
MEAN 1.1
VARIANCE, MEAN ESTIMATED 5.6E-2
VARIANCE, MEAN KNOWN 4.6667E-2
STANDARD DEVIATION, MEAN EST. 0.23664
STANDARD DEVIATION, MEAN KNOWN 0.21602

These results are readily verified by direct calculation.


The Subroutines 53

SORTING DATA, PERCENTILES AND CUMULATIVE FREQUENCY


DISTRIBUTION

Subroutine: AlAJrAlIlV

Description

Sorts data and determines their maximum, minimum, median and range. Computes
percentiles and cumulative frequency distribution for use in descriptive statistics.

Alethod

The given data are sorted in order of increasing magnitude by using the Shell Sort
method. This method is a well-known computer sorting technique and is covered
in many computing books (Lee and Lee, 1982). The maximum and minimum
values are obtained by selecting the first and last items of the sorted array respec-
tively. The range of the data is dermed as the difference between the maximum
and minimum values. The kth percentile of the data is the number t such that at
least k per cent of the data values are smaller or equal to t and also at least
(100 - k) per cent are equal to or larger than t. If t is found to lie at the centre
of the interval of two given data points, then the mean of the two data points is
selected. If t lies elsewhere in the interval, the nearest data point is chosen. The
median is dermed as the 50th percentile. The cumulative frequency is the total
frequency up to and including a particular item or class of data.
Input array A( ) is used for storing both input information and ordered output
data.

Subroutine Listing
2000 REM MAXIMUM AND MINIMUM
2010 REM
2020 REM SUBROUTINE: MAXMIN
2030 REM
2040 REM COMPUTES MAXIMUM, MINIMUM, RANGE, MEDIAN,
2050 REM PERCENTILES AND CUMULATIVE FREQUENCY DIST.
2060 REM
2070 REM VARIABLES:
2080 REM INPUT:
2090 REM A() •..•• INPUT DATA ARRAY
2100 REM NUMDAT .• NUMBER OF DATA
2110 REM PRCNT ••• REQUIRED PERCENTILE (\)
2120 REM OUTPUT:
2130 REM A() .•••. SORTED ARRAY
2140 REM F() ••••• ARRAY OF CUMULATIVE FREQUENCY
2150 REM MAX •.••• MAXIMUM VALUE
2160 REM MEDIAN .• MEDIAN VALUE
2170 REM MIN ••.•• MINIMUM VALUE
2180 REM NITM •••• NUMBER OF DIFFERENT ITEMS OF DATA
54 Advanced BASIC Scientific Subroutines

2190 REM PVAL .... PERCENTILE VALUE


2200 REM RANGE ... RANGE OF INPUT DATA
2210 REM V() ...•. ARRAY OF DIFFERENT ITEMS OF DATA
2220 REM LOCAL: ... P, Q, R, V1, V2
2230 REM ARRAY DIMENSIONS:
2240 REM A() ..... (NUMDAT + 1)
2250 REM V() ..... (NUMDAT)
2260 REM F() ..... (NUMDAT)
2270 REM
2280 REM SORT DATA
2290 GOSUB 2540
2300 REM
2310 REM MAXIMUM-MINIMUM, MEDIUM, RANGE
2320 LET MIN = A(1)
2330 LET MAX = A(NUMDAT)
2340 LET RANGE = MAX - MIN
2350 LET V1 = INT(NUMDAT*0.5) + 1
2360 LET V2 = NUMDAT - INT(NUMDAT*0.5)
2370 LET MEDIAN = (A(V1) + A(V2»/2
2380 REM
2390 REM PERCENTILES
2400 LET V1 = INT(NUMDAT*PRCNT*0.01) + 1
2410 LET V2 = NUMDAT - INT«100 - PRCNT)*NUMDAT*0.01)
2420 LET PVAL = (A(V1) + A(V2»/2
2430 REM
2440 REM CUMULATIVE FREQUENCY
2450 LET NITM = 1
2460 FOR P = 1 TO NUMDAT
2470 LET F(NITM) = P
2480 LET V(NITM) = A(P)
2490 IF A(P) <> A(P + 1) THEN LET NITM = NITM + 1
2500 IF P = NUMDAT THEN LET NITM = NITM - 1
2510 NEXT P
2520 RETURN
2530 REM
2540 REM SHELL SORT
2550 LET V1 = NUMDAT
2560 REM SET GAP LENGTH
2570 LET V1 = INT(V1/2)
2580 IF V1 = 0 THEN GOTO 2740
2590 FOR P = 1 TO NUMDAT - V1
2600 FOR Q = P TO 1 STEP -1
2610 LET R = Q + V1
2620 REM COMPARE DATA
2630 IF A(Q) > A(R) THEN GOTO 2660
2640 LET Q = 0
2650 GOTO 2700
2660 REM EXCHANGE DATA
2670 LET V2 = A(Q)
2680 LET A(Q) = A(R)
2690 LET A(R) = V2
2700 REM
2710 NEXT Q
2720 NEXT P
The Subroutines 55

2730 GOTO 2560


2740 REM
2750 RETURN

Sample Program

The following list gives the marks obtained in a test by a class of 60 students.
Arrange the list in increasing order of marks obtained and thus
(a) find maximum and minimum marks obtained,
(b) range of marks obtained,
(c) the median and the 80th percentile,
(d) tabulate cumulative frequency distribution.
If the pass mark was 30, find how many students failed the test.
40,26,60,70,90,40,40,20, 100,20,40, 10,40,5,40,30,20,40,30,40,
90,70,40,30,25,20,10,5,60,50,40,40,20,50, 70,80,5,10,40,60,
10,30,40,60,5,20,5,25,40,80,80,5, 70,40,30,50,20,50,60,50.
1000 REM SAMPLE PROGRAM: PMAXMIN
1010 REM FINDS MAXIMUM, MINIMUM, RANGE, MEDIAN,
1020 REM PERCENTILES AND CUMULATIVE FREQUENCY DIST.
1030 REM
1040 DIM A( 61)
1050 DIM F(60)
1060 DIM V( 60)
1070 REM
1080 REM SET INITIAL VALUES
1090 LET NUMOAT = 60
1100 LET PRCNT = 80
1110 REM
1120 REM READ DATA
1130 PRINT" INITIAL LIST"
1140 PRINT
1150 FOR l I T O NUMDAT
1160 READ A(I)
1170 PRINT A(I);
1180 IF INT(I/10) = 1/10 THEN PRINT
1190 NEXT I
1200 DATA 40, 26, 60, 70, 90, 40, 40, 20, 100, 20
1210 DATA 40, 10, 40, 5, 40, 30, 20, 40, 30, 40
122.0 DATA 90, 70, 40, 30, 25, 20, 10, 5, 60, 50
1230 DATA 40, 40, 20, 50, 70, 80, 5, 10, 40, 60
1240 DATA 10, 30, 40, 60, 5, 20, 5, 25, 40, 80
1250 DATA 80, 5, 70, 40, 30, 50, 20, 50, 60, 50
1260 REM
1270 REM SORT DATA AND PRINT RESULTS
1280 REM CALL SUBROUTINE MAXMIN
1290 GOSUB 2000
1300 PRINT
1310 PRINT" SORTED LIST"
56 Advanced BASIC Scientific Subroutines

1320 PRINT
1330 FOR I = 1 TO NUMDAT
1340 PRINT A(I);
1350 IF INT(I/10) = 1/10 THEN PRINT
1360 NEXT I
1370 PRINT
1380 PRINT" MINIMUM "; MIN
1390 PRINT" MAXIMUM "; MAX
1400 PRINT" MEDIAN = "; MEDIAN
1410 PRINT" RANGE "; RANGE
1420 PRINT PRCNT; "TH PERCENTILE = "; PVAL
1430 PRINT
1440 PRINT" CUMULATIVE FREQUENCY DISTRIBUTION"
1450 PRINT
1460 PRINT" MARK " , " CUMULATIVE FREQUENCY"
1470 FOR l I T O NITM
1480 PRINT V(I), " ", F(I)
1490 NEXT I
1500 END

>RUN
INITIAL LIST
40 26 60 70 90 40 40 20 100 20
40 10 40 5 40 30 20 40 30 40
90 70 40 30 25 20 10 5 60 50
40 40 20 50 70 80 5 10 40 60
10 30 40 60 5 20 5 25 40 80
80 5 70 40 30 50 20 50 60 50

SORTED LIST

5 5 5 5 5 5 10 10 10 10
20 20 20 20 20 20 20 25 25 26
30 30 30 30 30 40 40 40 40 40
40 40 40 40 40 40 40 40 40 40
50 50 50 50 50 60 60 60 60 60
70 70 70 70 80 80 80 90 90 100

MINIMUM 5
MAXIMUM 100
MEDIAN 40
RANGE 95
80TH PERCENTILE 60
CUMULATIVE FREQUENCY DISTRIBUTION
MARK CUMULATIVE FREQUENCY
5 6
10 10
20 17
25 19
26 20
The Subroutines 57

30 25
40 40
50 45
60 50
70 54
80 57
90 59
100 60

From the cumulative frequency table the total for marks less than 30 is 20,
and so 20 students fail the test.
58 Advanced BASIC Scientific Subroutines

COMPARISON OF TWO SAMPLE MEANS

Subroutine: COMMNS

Description

Computes basic statistical data for two samples and determines the value of
Student's t statistic with its associated degrees of freedom. It is assumed that the
two samples are taken from populations of equal variance. Paired and unpaired
data may be analysed.

Method

Let the subscripts 1 and 2 distinguish the parameters of two samples. For the
first sample of size nl the mean is given by
n1
Xl = ~ Xli
i=1

and an estimate of variance by

Xz and s~ are similarly defined for the second sample.


For unpaired data, the combined estimate of the population variance, az, is
given by
S2 = «n} - l)si + (nz - l)sD/(nl + nz - 2)
The standard error of the difference between the two sample means is
SE = sv'(1/nl + l/nz)
The value of the t test statistic is given by
t= IXI -xzl!SE
and the corresponding number of degrees of freedom is equal to nl + nz - 2.
For paired data, the standard error of the mean difference, d of n pairs of
data elements is given by
n
SE=v'(~(X}i-X2i)z/(n(n-l») where
;=1
n
d = I ~ (Xli - XZi) I/n
i=1

and the subscripts 1 and 2 are used to denote the first and second values of the
pair.
The Subroutines 59

The t statistic is determined from


t = djSE
and the corresponding number of degrees of freedom is equal to n - 1.

Subroutine Listing

2000 REM COMPARISON OF TWO SAMPLE MEANS


2010 REM
2020 REM SUBROUTINE: COMMNS
2030 REM
2040 REM COMPARES THE DIFFERENCE BETWEEN MEAN VALUES
2050 REM FOR PAIRED AND UNPAIRED SAMPLES AND COMPUTES
2060 REM T AND NUMBER OF DEGREES OF FREEDOM
2070 REM
2080 REM VARIABLES:
2090 REM INPUT:
2100 REM A() ..... INPUT DATA FOR SAMPLE A
2110 REM B() ..... INPUT DATA FOR SAMPLE B
2120 REM NUMA .... NUMBER OF DATA VALUES IN SAMPLE A
2130 REM NUMB .... NUMBER OF DATA VALUES IN SAMPLE B
2140 REM P$ .....• "PAIR" FOR PAIRED DATA
2150 REM "UNPAIR" FOR UNPAIRE) DATA
2160 REM OUTPUT:
2170 REM MEANA ..• MEAN OF SAMPLE A
2180 REM MEANB ... MEAN OF SAMPLE B
2190 REM MEANDF .. DIFFERENCE BETWEEN MEANS
2200 REM SE ...... STANDARD ERROR OF DIFFERENCE
2210 REM BETWEEN MEANS
2220 REM T ..•...• VALUE OF T VARIA1E
2230 REM VRA •.... ESTIMATE OF VARI\NCE FROM A
2240 REM VRB ..... ESTIMATE OF VARIANCE FROM B
2250 REM LOCAL: ... NUMA1, NUMA2, P. S1, S2
2260 REM ARRAY DIMENSIONS:
2270 REM A() ..... (NUMA)
2280 REM B() ..... (NUMB)
2290 REM
2300 REM CHECK DATA AND COMPUTE SUMMARY STATISTICS
2310 IF NUMA < 2 OR NUMB < 2 THEN GOTO 2550
2320 LET NUMA1 = NUMA - 1
2330 LET NUMB1 = NUMB - 1
2340 LET S1 = 0
2350 LET S2 = 0
2360 FOR P = 1 TO NUMA
2370 LET S1 S1 + A(P)
2380 LET S2 S2 + A(P)*A(P)
2390 NEXT P
2400 LET MEAN A S1/NUMA
2410 LET VRA = (S2 - MEANA*S1)/NUMA1
2420 LET S1 0
2430 LET S2 = 0
60 Advanced BASIC Scientific Subroutines

2440 FOR P = 1 TO NUMB


2450 LET Sl Sl + B(P)
2460 LET S2 = S2 + B(P)*B(P)
2470 NEXT P
2480 LET MEANB = Sl/NUMB
2490 LET VRB = (S2 - MEANB*Sl)/NUMB1
2500 LET MEANDF = ABS(MEANA - MEANB)
2510 REM
2520 REM COMPUTE VALUE OF T
2530 IF P$ "PAIR" THEN GOSUB 2590 ELSE GOSUB 2800
2540 RETURN
2550 REM
2560 PRINT" NUMA OR NUMB INVALID"
2570 PRINT" NUMA = "; NUMA; ", NUMB = "; NUMB
2580 END
2590 REM SUBROUTINE FOR PAIRED DATA
2600 REM
2610 IF NUMA <> NUMB THEN GOTO 2760
2620 LET S2 = 0
2630 FOR P= 1 TO NUMA
2640 LET Sl = A(P) - B(P)
2650 LET S2 = S2 + Sl*Sl
2660 NEXT P
2670 LET PVAR = (S2 - NUMA*MEANDF*MEANDF)/NUMA1
2680 IF PVAR = 0 THEN GOTO 2730
2690 LET SE = SQR(PVAR/NUMA)
2700 LET T = MEANDF/SE
2710 LET DF = NUMA1
2720 RETURN
2730 REM
2740 PRINT" EST. POP. VARIANCE ZERO, PAIRED DATA"
2750 END
2760 REM
2770 PRINT" NUMA AND NUMB NOT CONSISTENT WITH PAIRED"
2780 PRINT" DATA, NUMA = "; NUMA; It, NUMB = "; NUMB
2790 END
2800 REM SUBROUTINE FOR UNPAIRED SAMPLES
2810 REM
2820 IF P$ <> "UNPAIR" GOTO 2930
2830 LET DF = NUMA1 + NUMB1
2840 LET PVAR = VRA*NUMA1 + VRB*NUMB1
2850 LET PVAR = PVAR/(NUMA1 + NUMB1)
2860 IF PVAR = 0 THEN GOTO 2900
2870 LET SE = SQR(PVAR*(l/NUMA + l/NUMB»
2880 LET T = MEANDF/SE
2890 RETURN
2900 REM
2910 PRINT" EST. POP. VARIANCE ZERO, UNPAIRED DATA"
2920 END
2930 REM
2940 PRINT" INCORRECT DATA 'l'YPE AT P$, P$ "; P$
2950 END
The Subroutines 61

Sample Programs

Two samples of capacitors from a common batch were measured on instruments


A and B. The values recorded were
A: 83, 94, 93, 103, 108, 111, 115, 121, 126, 83, 129
B: 87, 95, 96, 103, 109, 117, 117, 124, 131
(a) Compare the means of the two samples and compute the t·statistic.
(b) The capacitors from sample A were also measured on instrument B and the
two readings for each individual capacitor recorded. The readings on B corres·
ponding with those obtained on A were:
92,97,103,104,106,110,124,122,129,90,131
Compute the value of the t statistic for these paired data.

Sample Program for (aJ


1000 REM SAMPLE PROGRAM: PCOMMNSl
1010 REM
1020 REM TWO SAMPLE MEANS COMPARED: UNPAIRED DATA
1030 REM
1040 REM ARRAY DIMENSIONS:
1050 DIM A(ll)
1060 DIM B( 9)
1070 REM
1080 DATA 83, 94, 93, 103, 108, 111, 115, 121, 126
1090 DATA 83, 129
1100 DATA 87, 95, 96, 103, 109, 117, 117, 124, 131
1110 REM
1120 REM READ INPUT DATA
1130 LET NUMA = II
1140 LET NUMB = 9
1150 LET P$ = "UNPAIR"
1160 FOR I = 1 TO NUMA
1170 READ A( I)
1180 NEXT I
1190 FOR I = 1 TO NUMB
1200 READ B(I)
1210 NEXT I
1220 REM
1230 REM COMPUTE DIFFERENCE BETWEEN MEANS
1240 REM AND PRINT RESULTS. CALL SUBROUTINE COMMNS
1250 GOSUB 2000
1260 PRINT II MEAN OF A "; MEANA
1270 PRINT II VARIANCE OF A "; VRA
1280 PRINT II MEAN OF B "; MEANB
1290 PRINT II VARIANCE OF B = "; VRB
62 Advanced BASIC Scientific Subroutines

1300 PRINT 11 DIFFERENCE BETWEEN MEANS "; MEANDF


1310 PRINT 11 SE OF DIFF. BETWEEN MEANS = 11; SE
1320 PRINT 11 VALUE OF T "; T
1330 PRINT 11 DEGREES OF FREEDOM "; DF
1340 END

>RUN
MEAN OF A = 106
VARIANCE OF A = 264.4
MEAN OF B 108.78
VARIANCE OF B = 215.19
DIFFERENCE BETWEEN MEANS 2.7778
SE OF DIFF. BETWEEN MEANS = 6.9997
VALUE OF T = 0.39684
DEGREES OF FREEDOM 18

The difference between the mean values of the two samples is small in com·
parison with the standard error and this is reflected in the value of the t statistic
of 0.397. Statistical tables show that a value of 2.1 with 18 degrees of freedom
would have been significant at the 5 per cent level. On the basis of this evidence
there is no reason to believe that the machines are producing different results.
Sample program for (b)

The analysis of this problem may be achieved by minor amendments to the sample
program used to solve (a).

1000 REM SAMPLE PROGRAM: PCOMMNS2


1010 REM
1020 REM COMPARISON OF MEAN DIFFERENCES, PAIRED DATA
1030 REM
1040 REM ARRAY DIMENSIONS:
1050 DIM A(ll)
1060 DIM B(ll)
1070 REM
1080 DATA 83, 94, 93, 103, 108, 111, 115, 121, 126
1090 DATA 83, 129, 92, 97, 103, 104, 106, 110, 124
1100 DATA 122, 129, 90, 131
1110 REM
1120 REM READ INPUT DATA
1130 LET NUMA = 11
1140 LET NUMB = 11
1150 LET P$ = "PAIR"
1160 FOR I = 1 TO NUMA
1170 READ A(I)
1180 NEXT I
1190 FOR I = 1 TO NUMB
1200 READ B(I)
1210 NEXT I
1220 REM
1230 REM COMPUTE DIFFERENCE BETWEEN MEANS
1240 REM AND PRINT RESULTS. CALL SUBROUTINE COMMNS
The Subroutines 63

1250 GOSUB 2000


1260 PRINT " MEAN OF A MEANA
1270 PRINT " VARIANCE OF A VRA
1280 PRINT " MEAN OF B MEANB
1290 PRINT " VARIANCE OF B VRB
1300 PRINT " DIFFERENCE BETWEEN MEANS MEANDF
1310 PRINT" SE OF DIFF. BETWEEN MEANS SE
1320 PRINT " VALUE OF T T
1330 PRINT " DEGREES OF FREEDOM OF
1340 END

>RUN
MEAN OF A 106
VARIANCE OF A 264.4
MEAN OF B 109.82
VARIANCE OF B 213.56
DIFFERENCE BETWEEN MEANS 3.8182
SE OF DIFF. BETWEEN MEANS 1.2779
VALUE OF T 2.9878
DEGREES OF FREEDOM 10

This value of 2.99 for t should be compared with 2.23 which corresponds to
the 5 per cent probability level for 10 degrees of freedom. This result is significant
and the conclusion is that there is likely to be a real difference in the performance
of the two machines. This difference was not revealed in the first analysis as the
variance in the capacitor values swamped that attributable to the machines. Pairing
the samples has made the check on the machines' performances much more
sensitive.

Note

This subroutine may be combined with TDISTR to produce a program capable


of indicating significance levels and confidence limits without recourse to statistical
tables.
64 Advanced BASIC Scientific Subroutines

CONTINGENCY TABLE

Subroutine: CONTIN

Description

Computes the value of chi.squared for an m x n contingency table. Intermediate


results are accessible. These include: row and column sums and expected values,
difference between observed and expected values, and the magnitude of chi·
squared for each cell.

Method

Let xii = observed result in row i of columnj


Xi' sum of observed values in the ith row
X.; sum of observed values in the jth column
ei; = expected value of the element in row i of columnj
t the grand total of observed values.
mn
t= r,r,Xi;
i I

ei; =Xi,X'jjt
X2 for each cell = (Xi; - eij)2 jeil
mn
Total X2 = ~ ~ (Xi; - eij)2 jei;
I J

Degrees of freedom = (m - 1) (n - 1)
where m and n are the number of row and column effects respectively.

Subroutine Listing

2000 REM CONTINGENCY TABLE


2010 REM
2020 REM SUBROUTINE: CONTIN
2030 REM
2040 REM ANALYSES AN M X N CONTINGENCY TABLE.
2050 REM COMPUTES EXPECTED VALUE, DEVIATION FROM
2060 REM EXPECTED VALUE, CHI-SQUARED FOR EACH
2070 REM ELEMENT, ROW, COLUMN AND CHI-SQUARED TOTALS.
2080 REM
2090 REM VARIABLES:
2100 REM INPUT:
2110 REM F() ..... F(I,J,1) ROWS 1 TO NUMA AND 1 TO
2120 REM NUMB CONTAIN INPUT DATA FOR A AND
2130 REM B EFFECTS RESPECTIVELY
2140 REM NUMA .... NUMBER OF B EFFECTS
The Subroutines 65

2150 REM NUMB .... NUMBER OF A EFFECTS


2160 REM OUTPUT:
2170 REM DF .•.... DEGREES OF FREEDOM
2180 REM F() ..... F(I,J,2) CONTAINS EXPECTED VALUE
2190 REM F(I,J,3) CONTAINS THE DEVIATION
2200 REM FROM EXPECTED VALUE
2210 REM F(I,J,4) CONTAINS CHI-SQUARED
2220 REM ROW NUMA + 1 CONTAINS COLUMN TOTAL
2230 REM COL. NUMB + 1 CONTAINS ROW TOTALS
2240 REM BOX NUMB + 1, NUMA + 1 CONTAINS
2250 REM THE GRAND TOTALS
2260 REM NUMAI ... NUMA + 1
2270 REM NUMBl ... NUMB + 1
2280 REM LOCAL: ... P, Q, R, VI
2290 REM ARRAY DIMENSIONS:
2300 REM F(} ...... (NUMAl,NUMBl,4)
2310 REM
2320 REM SET INITIAL VALUES AND COMPUTE ROW AND
2330 REM COLUMN SUMS
2340 LET NUMAI = NUMA + 1
2350 LET NUMBI = NUMB + 1
2360 FOR P = 1 TO NUMA
2370 FOR R = 1 TO 4
2380 LET F(P,NUMBl,R) o
2390 NEXT R
2400 FOR Q = 1 TO NUMB
2410 LET F(P,NUMBl,l} F(P,NUMBl,l} + F(P,Q,I)
2420 NEXT Q
2430 NEXT P
2440 FOR Q = 1 TO NUMBI
2450 FOR R = 1 TO 4
2460 LET F(NUMAl,Q,R) o
2470 NEXT R
2480 FOR P = 1 TO NUMA
2490 LET F(NUMAl,Q,I} F(NUMA1,Q,I) + F(P,Q,I)
2500 NEXT P
2510 NEXT Q
2520 REM
2530 REM COMPUTE EXPECTED VALUE, DIFFERENCE AND
2540 REM CHI-SQUARED AND CHECK EXPECTED VALUE
2550 FOR P = 1 TO NUMA
2560 FOR Q = 1 TO NUMB
2570 LET VI = F(NUMAl,Q,I)*F(P,NUMBl,l)
2580 LET F(P,Q,2} = Vl/F(NUMAl,NUMBl,l)
2590 IF ABS(F(P,Q,2}) < 1 THEN GO TO 2740
2600 LET F(P,Q,3} = F(P,Q,I} - F(P,Q,2)
2610 LET F(P,Q,4} = F(P,Q,3)*F(P,Q,3)/F(P,Q,2)
2620 LET F(P,NUMBl,2} F(P,NUMBl,2) + F(P,Q,2)
2630 LET F(P,NUMBl,3} F(P,NUMBl,3) + F(P,Q,3}
2640 LET F(P,NUMBl,4} = F(P,NUMBl,4) + F(P,Q,4)
2650 NEXT Q
2660 FOR Q = 1 TO NUMBI
2670 LET F ( NUMAl, Q, 2 ) F(NUMAl,Q,2} + F(P,Q,2}
2680 LET F(NUMAl,Q,3) F(NUMAl,Q,3) + F(P,Q,3}
2690 LET F ( NUMAl, Q, 4 ) F(NUMAl,Q,4} + F(P,Q,4}
66 Advanced BASIC Scientific Subroutines

2700 NEXT Q
2710 NEXT P
2720 LET DF = (NUMA - l)*(NUMB - 1)
2730 RETURN
2740 REM
2750 PRINT" EXPECTATION < 1 AT ROW"; P; " COL. "; Q
2760 END

Sample Program

Batches of ceramic capacitors are fired in one of four kilns and at the end of
their processing are subjected to severe environmental testing. The number of
batches that passed and failed the tests over the period of a year were recorded
and this information is presented in the table below.
Use a contingency table in conjunction with the x: test to check whether
there is evidence that the quality of output from the kilns is significantly different.

Quality Assurance
Kiln pass fail

1 22 16
2 24 8
3 25 9
4 18 20

1000 REM SAMPLE PROGRAM: PCONTIN


1010 REM
1020 REM CHI-SQUARED FOR AN M X N CONTINGENCY TABLE
1030 REM
1040 REM VARIABLES:
1050 REM P$() •..•• LABELS FOR ROWS
1060 REM ARRAY DIMENSIONS:
1070 DIM F(5,3,4)
1080 DIM P$(4)
1090 REM
1100 DATA 22, 16, 24, 8, 25, 9, 18, 20
1110 REM
1120 REM READ INPUT DATA AND SET INITIAL VALUES
1130 LET NUMA = 4
1140 LET NUMB = 2
1150 LET P$(l) = " OBSERVED "
1160 LET P$(2) " EXPECTED "
1170 LET P$(3) = " DIFFERENCE "
1180 LET P$(4) = .. CHI-SQUARED"
1190 FOR I = 1 TO NUMA
1200 FOR J = 1 TO NUMB
1210 READ F(I,J,l)
The Subroutines 67

1220 NEXT J
1230 NEXT I
1240 REM
1250 REM COMPUTE CONTINGENCY TABLE AND PRINT RESULTS
1260 REM CALL SUBROUTINE CONTIN
1270 GOSUB 2000
1280 PRINT " EFFECT B AND TOTAL"
1290 PRINT " EFFECT A"
1300 FOR l I T O NUMA1
1310 IF I = NUMA1 THEN PRINT " TOTAL"
1320 FOR K = 1 TO 4
1330 PRINT P$(K);
1340 FOR J = 1 TO NUMB1
1350 IF J = NUMB1 THEN PRINT " ",.
1360 PRINT F(I,J,K);
1370 NEXT J
1380 PRINT
1390 NEXT K
1400 PRINT
1410 NEXT I
1420 PRINT " DEGREES OF FREEDOM "; DF
1430 END

>RUN
EFFECT B AND TOTAL
EFFECT A
OBSERVED 22 16 38
EXPECTED 23.8169 14.1831 38
DIFFERENCE -1. 8169 1.8169 0
CHI-SQUARED 0.138605 0.232751 0.371356

OBSERVED 24 8 32
EXPECTED 20.0563 11. 9437 32
DIFFERENCE 3.94366 -3.94366 0
CHI-SQUARED 0.775439 1.30215 2.07759

OBSERVED 25 9 34
EXPECTED 21. 3099 12.6901 34
DIFFERENCE 3.69014 -3.69014 0
CHI-SQUARED 0.639007 1. 07305 1.71206

OBSERVED 18 20 38
EXPECTED 23.8169 14.1831 38
DIFFERENCE -5.8169 5.8169 0
CHI-SQUARED 1. 42069 2.38568 3.80637

TOTAL
OBSERVED 89 53 142
EXPECTED 89 53 142
DIFFERENCE 0 0 0
CHI-SQUARED 2.97374 4.99363 7.96737

DEGREES OF FREEDOM = 3
68 Advanced BASIC Scientific Subroutines

It will be found by reference to tables that the 0.05 level of,c for 3 degrees
of freedom is 7.815. The analysis gives a value of 7 .97; this result may therefore
be regarded as statistically significant. Kiln 4 contributes the largest part of the
value for X2 and a further investigation would probably start with an examination
of the quality of output from this apparatus.

Notes

1. The significance of this result may be tested directly with the aid of subroutine
CHISQD.
2. Data for use in contingency tables should be organised so that low expected
values are avoided. An error message is produced if the magnitude of the expected
value is less than 1 in any cell.
The Subroutines 69

FACTORIALS, PERMUTAnONS AND COMBINA nONS

Subroutine: PERCOM

Description

Computes the natural logarithm of n!,P(n, r), and C(n, r).


Requires subroutine LNGAMM.

Method

n! = n(n - 1) (n - 2) ... I
0!=1 n=0,1,2 ...
n!
P(n,r)= - - r=0,1,2 ... r";'n
(n - r)!
n!
C(n,r)= - - - r=0,1,2 ...
(n - r)!r!
The factorials are computed with the aid of the gamma function:

a! = rea + 1)

Subroutine Listing

3000 REM FACTORIALS, PERMUTATIONS AND COMBINATIONS


3010 REM
3020 REM SUBROUTINE: PERCOM
3030 REM
3040 REM EVALUATES THE NATURAL LOGARITHM OF N!,
3050 REM P(N,R) AND C(N,R) FOR POSTIVE INTEGRAL
3060 REM VALUES OF PARAMETERS NAND R.
3070 REM REQUIRES SUBROUTINE LNGAMM.
3080 REM
3090 REM VARIABLES:
3100 REM INPUT:
3110 REM NF ...... NUMBER FOR WHICH THE FACTORIAL IS
3120 REM REQUIRED OR FROM WHICH Rl IS
3130 REM SELECTED
3140 REM R1 ...... NUMBER SELECTED FROM NF
3150 REM OUTPUT:
3160 REM NLNF .... LN(NFI)
3170 REM NLNCR ... LN(C(NF,R1»
3180 REM NLNPR ... LN(P(NF,Rl»
3190 REM
3200 REM CHECK VALIDITY OF INPUT DATA
3210 IF NF < 0 OR Rl < 0 OR NF < Rl THEN GOTO 3360
3220 IF INT(NF) < NF OR INT(R1) < Rl THEN GOTO 3360
3230 REM
70 Advanced BASIC Scientific Subroutines

3240 REM COMPUTE RESULTS. CALL SUBROUTINE LNGAMM


3250 REM FOR EACH FACTORIAL COMPUTATION
3260 LET ALPHA = NF + 1
3270 GOSUB 2000
3280 LET NLNF = NLGGAM
3290 LET ALPHA = NF - R1 + 1
3300 GOSUB 2000
3310 LET NLNPR = NLNF - NLGGAM
3320 LET ALPHA = R1 + 1
3330 GOSUB 2000
3340 LET NLNCR = NLNPR - NLGGAM
3350 RETURN
3360 REM
3370 PRINT" NF OR R1 NOT A POSITIVE WHOLE NUMBER"
3380 PRINT" OR NF < R1, NF = "; NF; ", R1 = "; R1
3390 END

Sample Program

Calculate the number of ways a deck of 52 cards may be arranged.


Determine the number of ways in which 13 cards may be dealt from a pack
of 52 and the number of different hands of 13 cards that are possible. Comment
on the probability of being dealt a bridge hand which consists of 13 cards of the
same suit.

1000 REM SAMPLE PROGRAM: PPERCOM


1010 REM
1020 REM COMPUTES A) THE NUMBER OF WAYS OF ARRANGING
1030 REM NF CARDS AND B) THE NUMBER OF WAYS R1 CARDS
1040 REM MAY BE DEALT FROM A PACK OF NF WITH AND
1050 REM WITHOUT REGARD TO ORDER
1060 REM
1070 REM SET INITIAL VALUES, CALL SUBROUTINE PERCOM
1080 LET NF = 52
1090 LET R1 = 13
1100 GOSUB 3000
1110 PRINT" LN( NUMBER OF WAYS OF ARRANGING) "; NF;
1120 PRINT" CARDS = "; NLNF
1130 PRINT" NUMBER OF WAYS TO DEAL "; R1; " CARDS"
1140 PRINT" WITH REGARD TO ORDER "; EXP (NLNPR)
1150 PRINT" WITHOUT REGARD TO ORDER = "; EXP(NLNCR)
1160 END

>RUN
LN( NUMBER OF WAYS OF ARRANGING) 52 CARDS 156.36084
NUMBER OF WAYS TO DEAL 13 CARDS
WITH REGARD TO ORDER 3.9542424E21
WITHOUT REGARD TO ORDER = 6.3501353E11
The Subroutines 71

The number of possible arrangements of 52 cards is exp(l56.36084). The


number of ways of dealing 13 cards is 3.95424 x 1021 and the number of
possible hands 6.35013 x 1011. The probability of being dealt 13 cards of the
same suit is extremely small, approximately 6.3 x 10- 12 , (4/(C(n, r)).
72 Advanced BASIC Scientific Subroutines

2.4 Analysis of Variance


ONE-WAY ANALYSIS OF VARIANCE

Subroutine: OWAOVA

Description

Computes an Analysis of Variance table (ANOV A) from which the hypothesis


that there is no difference in the values of several sample means may be tested.
Some summary statistics for each sample are also computed.

Method

Data on the samples to be tested are stored in array F ( ). Let k be the number of
samples to be tested and n the number of observations in each sample. The
information on the samples is contained in columns 1 to k of F( ) and that on
the observations in rows 1 to n. The values of the observations on the ith sample
are thusxli,x2j, ... ,Xni.
The grand mean is given by
k n
X = ~ ~xi;/nk
i=1 ;=1

and the estimate of the variance of the observations in sample i is


n
sf = ~ (Xii - x/)2/(n - I)
/=1

The ANOVA table is stored in array CO and computed as indicated below:

Source of Degrees of Sum of Mean F-ratio


variation freedom squares square

Between C(1, 1) = C(1, 2) = C(I, 3) = C(1, 4) =


samples k
k-l n ~(Xi _X)2 C(l, 2)/C(1, 1) C(1, 3)/C(2, 3)
i=1

Within C(2, 1) = C(2, 2) = C(2, 3) =


samples k n
ken - 1) ~ ~ (Xii - Xi)2 C(2, 2)/C(2, 1)
/=1/=1

Total C(3, 1) = C(3,2) =


C(1, 1) + C(2, 1) C(1, 2) + C(2, 2)

Analysis of Variance Table


The Subroutines 73

Subroutine Listing

2000 REM ONE-WAY ANALYSIS OF VARIANCE


2010 REM
2020 REM SUBROUTINE: OWAOVA
2030 REM
2040 REM COMPUTES ANOVA TABLE FOR A ONE-WAY ANALYSIS
2050 REM
2060 REM VARIABLES:
2070 REM INPUT:
2080 REM F() •.... COLS. 1 TO NUMSAM CONTAIN DATA ON
2090 REM THE SAMPLES. ROWS 1 TO NUMANL
2100 REM CONTAIN THE INDIVIDUAL ANALYSIS
2110 REM VALUES FOR EACH SAMPLE
2120 REM NUMANL .• NUMBER OF ANALYSES IN EACH SAMPLE
2130 REM NUMSAM .• NUMBER OF SAMPLES OR TREATMENTS
2140 REM OUTPUT:
2150 REM C() •.... ANOVA TABLE
2160 REM COL.1 DEGREES OF FREEDOM
2170 REM COL.2 SUM OF SQUARES
2180 REM COL.3 MEAN SQUARE
2190 REM COL.4 F-RATIO
2200 REM ROW 1 BETWEEN SAMPLE VARIATION
2210 REM ROW 2 WITHIN SAMPLE VARIATION
2220 REM ROW 3 TOTAL
2230 REM GRNDMN .. GRAND MEAN
2240 REM H() ...•. CONTAINS INTERMEDIATE RESULTS.
2250 REM COLS. 1 TO NUMSAM CONTAIN RESULTS
2260 REM FOR RESPECTIVE SAMPLES
2270 REM COL. NUMSAM + 1 CONTAINS TOTAL OF
2280 REM PRECEDING COLUMNS
2290 REM ROW 1 SUM OF DATA VALUES
2300 REM ROW 2 SUM OF SQUARES
2310 REM ROW 3 CORRECTION FOR SUM SQUARES
2320 REM ROW 4 SUM OF SQUARES ABOUT MEAN
2330 REM ROW 5 SAMPLE MEAN
2340 REM ROW 6 SAMPLE VARIANCE
2350 REM LOCAL: ... NUMSM1, P, Q
2360 REM ARRAY DIMENSIONS:
2370 REM C() ••••• (3,4)
2380 REM F() .••.. (NUMANL,NUMSAM)
2390 REM H ( ) ..... ( 6, NUMSAM + 1)
2400 REM
2410 REM CHECK NUMBER OF SAMPLES AND ANALYSES
2420 IF NUMSAM < 2 OR NUMANL < 2 THEN GOTO 2840
2430 REM
2440 REM COMPUTE ARRAY H()
2450 FOR P = 1 TO NUMSAM
2460 H(l,P) = 0
2470 H(2,P) = 0
2480 FOR Q = 1 TO NUMANL
2490 H(l,P) = H(l,P) + F(Q,P)
2500 H(2,P) = H(2,P) + F(Q,P)*F(Q,P)
2510 NEXT Q
2520 H(5,P) = H(l,P)/NUMANL
74 Advanced BASIC Scientific Subroutines

2530 H(3,P) H(1,P)*H(5,P)


2540 H(4,P) H(2,P) - H(3,P)
2550 H(6,P) H(4,P)/(NUMANL - 1)
2560 NEXT P
2570 LET NUMSM1 = NUMSAM + 1
2580 FOR P = 1 TO 6
2590 LET H(P,NUMSM1) = 0
2600 FOR Q = 1 TO NUMSAM
2610 H(P,NUMSM1) = H(P,NUMSM1) + H(P,Q)
2620 NEXT Q
2630 NEXT P
2640 LET GRNDMN = H(1,NUMSM1)/(NUMSAM*NUMANL)
2650 REM
2660 REM CALCULATE ANOVA TABLE
2670 LET C(l,l) NUMSAM - 1
2680 LET C(2,1) NUMSAM*(NUMANL - 1)
2690 LET C(3,1) C(l,l) + C(2,1)
2700 LET C(1,2) H(3,NUMSM1) - H(1,NUMSM1)*GRNDMN
2710 LET C(2,2) H(4,NUMSM1)
2720 LET C(3,2) C(1,2) + C(2,2)
2730 REM
2740 REM CHECK FOR SMALL RESIDUAL
2750 IF C(2,2)/C(3,2) > 1E-5 THEN GOTO 2790
2760 LET C(2,2) = C(3,2)*lE-5
2770 PRINT" NOTE: LOW VALUE OF RESIDUAL,";
2780 PRINT " LESS THAN COMPUTED"
2790 REM
2800 LET C(1,3) C(1,2)/C(1,1)
2810 LET C(2,3) C(2,2)/C(2,1)
2820 LET C(1,4) C(1,3)/C(2,3)
2830 RETURN
2840 REM
2850 PRINT" NUMBER OF SAMPLES OR NUMBER OF ANALYSES";
2860 PRINT" TOO SMALL"
2870 PRINT" NUMSAM = "; NUMSAM; ", NUMANL = "; NUMANL
2880 END

Sample Program

Five similar machines are employed to cut tube to lengths of 20 mm. Eight samples
of tube were taken from each machine and the measurements displayed in a table
(see opposite). (a) Determine the mean lengths of the tubes cut by each machine and
(b) produce an analysis ofvariance table to enable the hypothesis that all five
machines produce tube of the same average length to be tested.
The Subroutines 75

Machine
Observation
1 2 3 4 5
number
1 17.5 16.9 21.4 23.2 23.4
2 17.3 15.2 19.1 19.6 15.4
3 19.4 20.5 23.5 21.6 24.6
4 17.8 17.8 21.8 19.5 16.9
5 21.9 20.9 21.9 18.1 19.6
6 17.9 23.5 18.7 18.1 21.1
7 17.8 24.8 21.6 19.2 16.9
8 17.4 24.4 18.3 21.5 22.8

1000 REM SAMPLE PROGRAM: POWAOVA


1010 REM
1020 REM ONE-WAY ANALYSIS OF VARIANCE ON
1030 REM MACHINE PERFORMANCE
1040 REM
1050 REM ARRAY DIMENSIONS:
1060 DIM C(3,4)
1070 DIM F(8.5)
1080 DIM H(6,6)
1090 REM
1100 DATA 17.5, 16.9. 21. 4, 23.2, 23.4
1110 DATA 17.3, 15.2, 19.1, 19.6, 15.4
1120 DATA 19.4, 20.5, 23.5, 21. 6, 24.6
1130 DATA 17.8, 17.8. 21. 8, 19.5, 16.9
1140 DATA 21. 9, 20.9, 21. 9, 18.1, 19.6
1150 DATA 17.9, 23.5, 18.7, 18.1, 21.1
1160 DATA 17.8, 24.8, 21. 6, 19.2, 16.9
1170 DATA 17.4, 24.4, 18.3, 21.5, 22.8
1180 REM
1190 REM SET INITIAL VALUES AND READ INPUT DATA
1200 LET NUMANL = 8
1210 LET NUMSAM = 5
1220 FOR I = 1 TO NUMANL
1230 FOR J = 1 TO NUMSAM
1240 READ F(I,J)
1250 NEXT J
1260 NEXT I
1270 REM
1280 REM COMPUTE ANOVA TABLE
1290 REM CALL SUBROUTINE OWAOVA
1300 GOSUB 2000
1310 PRINT " SAMPLE MEANS AND VARIANCES"
1320 PRINT " SAMPLE MEAN VARIANCE"
1330 FOR I = 1 TO NUMSAM
1340 PRINT I, H(5,I), H(6,I)
76 Advanced BASIC Scientific Subroutines

1350 NEXT I
1360 PRINT " GRAND MEAN = " ,. GRNDMN
1370 PRINT
1380 PRINT " ANOVA TABLE"
1390 PRINT
1400 PRINT " SOURCE D.F. SUM SO MEAN SQ";
1410 PRINT " F-RATIO"
1420 PRINT
1430 PRINT " BETWEEN"; C(l,l), C(1,2), C(1,3), C(1,4)
1440
1450
PRINT ..
PRINT "
SAMPLES"
WITHIN ...
, C(2,l), C(2,2), C(2,3)
1460 PRINT " SAMPLES"
1470 PRINT " TOTAL II; C(3,l), C(3,2)
1480 END

>RUN
SAMPLE MEANS AND VARIANCES
SAMPLE MEAN VARIANCE
1 18.375 2.462143
2 20.5 13.02857
3 20.7875 3.435536
4 20.1 3.32
5 20.0875 11. 74982
GRAND MEAN = 19.97

ANOVA TABLE

SOURCE D.F. SUM SO MEAN SO F-RATIO

BETWEEN 4 28.19149 7.047873 1. 036572


SAMPLES
WITHIN 35 237.9725 6.799214
SAMPLES
TOTAL 39 266.164

For 4 and 35 degrees of freedom the 0.05 value ofF is 2.5. The computed
ratio is less than this and consequently, on the basis of this trial there is no reason
to reject the hypothesis.

Notes

1. For this analysis the number of observations in each sample must be equal.
2. This subroutine includes a check for a low value of residual. Its action is
similar to that described in the notes section of the two-way analysis.
3. Scheffe (1959), Chatfield (1970), Davis and Goldsmith (1972) and Wonnacott
and Wonnacott (1981) are suggested for further reading.
The Subroutines 77

TWO-WAY ANALYSIS OF VARIANCE WITH AND WITHOUT REPLICATION

Subroutine: TWAOVA

Description

Computes an Analysis of Variance table (ANOVA) for a two-way classification


with one or more observations per cell. The row, column and cell means are
computed for the input data.

Method

The ANOVA tables below indicate the method of computation. Running the
subroutine causes the results of these calculations to be stored in array C(). The
special case of where there is only one observation per cell is treated separately
and the row containing the interaction effect is set to zero.
The dot notation is used to identify a row, column or cell mean in order. In
the tables, A and B are the number of effects to be analysed and R the number
of replicates.
Prior to calling subroutine TWAOVA it is necessary to store the input in the
three-dimensional array F( ). The subroutine holds the mean values of each cell,
together with the row and column means and the grand (or corner) mean, in
array M().

Sourceo! Degreeso! Sumo! Mean F-ratio


variation freedom squares square

A effect C(1, 1) = C(1, 2) = C(1, 3) = C(1, 4) =


A-I B~(Xi. -x.Y C(1, 2)/C(1, 1) C(I, 3)/C(4, 3)
i
B effect C(2, 1) = C(2, 2) = C(2, 3) = C(2, 4) =
B-1 A'T.(x.j - x.Y C(2, 2)/C(2, 1) C(2, 3)/C(4, 3)
I
Interaction C(3, 1) = C(3, 2) = C(3, 3) = C(3, 4) =
0 0 0 0
Residual C(4, 1) = C(4, 2) = C(5, 2) C(4, 3) =
(A -1)(B -1) -C(1,2) C(4,2)/C(4,1)
-C(2,2)
Total C(5, 1) = C(5, 2) =
AB-l ~~(xil-x.Y
I I

Analysis o! Variance Table - Without Replicates


~

Sourceo! Degreeso! Sumo! Mean F-ratio


variation freedom squares square

A effect C{1,1)= C{1, 2) = C{1,3)= C{1,4)= ~


~
A-I BR~(Xi .. - x .. Y C{1, 2)/C(1, 1) C{1, 3)/C{4, 3) ~
i ;:s
l')

B effect C(2, 1) = C{2, 2) = C{2, 3) = C(2, 4) =


a
B-1 AR~(X.j. - x .. Y C(2, 2)/C(2, 1) C(2, 3)/C(4, 3) ~
/ ~
C'l
Interaction C(3,1)= C(3, 2) = R~~(Xij. C(3, 3) = C(3, 4) = ~
~.
I / ;:s
(A - 1) (B - 1) C(3, 2)/C{3, 1) C(3, 3)/C{4, 3)
-x·I.. - x ./.. +x . .• )2 §
l')

Residual C(4, 1) = C{4, 2) = C{5, 2) C(4,3)= ~


~
AB(R -1) - C(I, 2) - C(2, 2) - C(3, 2) C{ 4, 2)/C{4, 1) ~
l::
Total C(5, 1) = C(5, 2) = 5·
ABR-1 ~~~(X ..k - ~
1/
i j k
x ... )2

Analysis o! Variance Table - With Replicates


The Subroutines 79

Subroutine Listing

2000 REM TWO-WAY ANALYSIS OF VARIANCE


2010 REM
2020 REM SUBROUTINE: TWAOVA
2030 REM
2040 REM COMPUTES ANOVA TABLE FOR A TWO-WAY ANALYSIS
2050 REM WITH AND WITHOUT REPLICATES
2060 REM
2070 REM VARIABLES:
2080 REM INPUT:
2090 REM F() .•... ROWS 1 TO NUMA CONTAIN A EFFECTS
2100 REM COLS. 1 TO NUMB CONTAIN B EFFECTS
2110 REM ELEMENTS 1 TO NUMR CONTAIN
2120 REM REPLICATES
2130 REM NUMA .•.. NUMBER OF A EFFECTS
2140 REM NUMB .... NUMBER OF B EFFECTS
2150 REM NUMR .... NUMBER OF REPLICATES
2160 REM OUTPUT:
2170 REM C() ...•. ANOVA TABLE
2180 REM COL.1 DEGREES OF FREEDOM
2190 REM COL.2 SUM OF SQUARES
2200 REM COL.3 MEAN SQUARE
2210 REM COL.4 F-RATIO
2220 REM ROW 1 A EFFECTS
2230 REM ROW 2 B EFFECTS
2240 REM ROW 3 INTERACTION
2250 REM ROW 4 RESIDUAL
2260 REM ROW 5 TOTAL
2270 REM M() ...•• ARRAY OF MEANS
2280 REM ROWS 1 TO NUMA AND COLS 1 TO NUMB
2290 REM CONTAIN THE MEANS OF REPLICATES
2300 REM AND CORRESPOND WITH F(). ROW
2310 REM NUMA + 1 CONTAINS MEANS OF COLS 1
2320 REM TO NUMA. COL. NUMB + 1 CONTAINS
2330 REM MEANS OF ROWS 1 TO NUMA.
2340 REM M(NUMA + 1, NUMB + 1) CONTAINS THE
2350 REM GRAND MEAN.
2360 REM LOCAL: ... K1, NUMA1, NUMB1, P, Q, R
2370 REM ARRAY DIMENSIONS:
2380 REM C() ..... (5,4)
2390 REM F() ..... (NUMA,NUMB,NUMR)
2400 REM M() .•.•• (NUMA + 1,NUMB + 1)
2410 REM
2420 REM CHECK NUMBER OF EFFECTS AND ELEMENTS
2430 IF NUMA < 2 OR NUMB < 2 THEN GOTO 3380
2440 IF NUMR < 1 THEN GOTO 3380
2450 REM
2460 REM COMPUTE ARRAY OF MEANS M()
2470 LET NUMAl = NUMA + 1
2480 LET NUMBl = NUMB + 1
2490 FOR P = 1 TO NUMA
2500 LET M(P,NUMB1) = 0
2510 FOR Q = 1 TO NUMB
80 Advanced BASIC Scientific Subroutines

2520 LET H(P,O) = 0


2530 FOR R = 1 TO NUHR
2540 H(P,O) = H(P,O) + F(P,O,R)
2550 NEXT R
2560 LET H(P,O) = H(P,O)/NUHR
2570 LET H(P,NUHB1) = H(P,NUHB1) + H(P,O)
2580 LET H(NUHA1,Q) = H(NUHA1,Q) + H(P,Q)
2590 NEXT 0
2600 LET H(P,NUHB1) = H(P,NUHB1)/NUHB
2610 NEXT P
2620 FOR P = 1 TO NUHB1
2630 LET H(NUHA1,P) = 0
2640 FOR Q = 1 TO NUHA
2650 LET H(NUMA1,P) = H(NUMA1,P) + M(Q,P)
2660 NEXT Q
2670 M(NUHAl,P) = M(NUMAl,P)/NUHA
2680 NEXT P
2690 REM
2700 REM CALCULATE SS ATTRIBUTABLE TO A AND B
2710 LET Kl = NUMA*NUMB*NUHR
2720 LET K1 = Kl*M(NUMA1,NUMB1)*H(NUHA1,NUMB1)
2730 LET C(1,2) = 0
2740 FOR P = 1 TO NUHA
2750 LET C(1,2) = C(1,2) + M(P,NUHBl)*H(P,NUHB1)
2760 NEXT P
2770 LET C(1,2) = NUHB*NUMR*C(1,2) - K1
2780 LET C(2,2) = 0
2790 FOR P = 1 TO NUMB
2800 LET C(2,2) = C(2,2) + H(NUMA1,P)*H(NUHA1,P)
2810 NEXT P
2820 LET C(2,2) = NUMA*NUMR*C(2,2) - K1
2830 REH
2840 REM CALCULATE INTERACTION AND TOTAL SS
2850 IF NUMR > 1 THEN GOTO 2900
2860 FOR I = 1 TO 4
2870 LET C(3,I) = 0
2880 NEXT I
2890 GOTO 2980
2900 REM
2910 LET C(3,2) = 0
2920 FOR P = 1 TO NUHA
2930 FOR Q = 1 TO NUHB
2940 LET C(3,2) = C(3,2) + M(P,O)*M(P,Q)
2950 NEXT Q
2960 NEXT P
2970 LET C(3,2) = NUMR*C(3,2) - K1 - C(1,2) - C(2,2)
2980 REH
2990 LET C(5,2) = 0
3000 FOR P = 1 TO NUMA
3010 FOR Q = 1 TO NUHB
3020 FOR R = 1 TO NUMR
3030 LET C(5,2) = F(P,Q,R)*F(P,Q,R) + C(5,2)
3040 NEXT R
3050 NEXT Q
3060 NEXT P
The Subroutines 81

3070 LET C(5,2) = C(5,2) - K1


3080 LET C(4,2) = C(5,2) - C(3,2) - C(1,2) - C(2,2)
3090 REM
3100 REM CHECK FOR SMALL RESIDUAL
3110 IF C(4,2)/C(5,2) > 1E-5 THEN GOTO 3150
3120 LET C(4,2) = C(5,2)*lE-5
3130 PRINT" NOTE: LOW VALUE OF RESIDUAL,"
3140 PRINT If TRUE VALUE LESS THAN COMPUTED"
3150 REM
3160 REM CALCULATE ANOVA
3170 LET C(l,l) = NUMA - 1
3180 LET C(2,1) = NUMB - 1
3190 LET C(5,1) = NUMA*NUMB*NUMR - 1
3200 IF NUMR = 1 THEN GO TO 3290
3210 LET C(3,1) = C(1,1)*C(2,1)
3220 LET C(4,1) = NUMA*NUMB*(NUMR - 1)
3230 LET C(4,3) = C(4,2)/C(4,1)
3240 FOR P = 1 TO 4
3250 LET C(P,3) C(P,2)/C(P,1)
3260 LET C(P,4) = C(P,3)/C(4,3)
3270 NEXT P
3280 GOTO 3360
3290 REM
33 0 0 LET C( 4 , 1 ) (NUMA - 1) * (NUMB - 1)
3310 LET C(1,3) C(1,2)/C(1,1)
3320 LET C(2,3) C(2,2)/C(2,1)
3330 LET C(4,3) = C(4,2)/C(4,1)
3340 LET C(1,4) C(1,3)/C(4,3)
3350 LET C(2,4) C(2,3)/C(4,3)
3360 REM
3370 RETURN
3380 REM
3390 PRINT" NUMBER OF EFFECTS/REPLICATES TOO SMALL"
3400 PRINT" NUMA = "; NUMA; ", NUMB = "; NUMB;
3410 PRINT ", NUMR = "; NUMR
3420 END

Sample Programs

1. Without Replication

The average hourly outputs of three workers when operating one of five machines
over a period of time is shown in the able overleaf. Construct an ANOVA table to
assess whether it is likely that a Significant difference exists between the perform-
ances of the operators and machines.
82 Advanced BASIC Scientific Subroutines

Machine
Operator (effect B)
(effect A)

1 55.2 59.6 48.8


2 56.5 53.5 46.3
3 59.5 54.0 56.1
4 58.4 53.3 43.7
5 59.4 56.2 52.9

Output of Operators and Machines

1000 REM SAMPLE PROGRAM: PTWAOVA1


1010 REM
1020 REM TWO-WAY ANOVA WITH ONE OBSERVATION PER CELL
1030 REM
1040 REM ARRAY DIMENSIONS:
1050 DIM C(5,4)
1060 DIM F(5,3,1)
1070 DIM M(6,4)
1080 REM
1090 DATA 55.2, 59.6, 48.8
1100 DATA 56.5, 53.5, 46.3
1110 DATA 59.5, 54.0, 56.1
1120 DATA 58.4, 53.3, 43.7
1130 DATA 59.4, 56.2, 52.9
1140 REM
1150 REM SET INITIAL VALUES AND READ INPUT DATA
1160 LET NUMA = 5
1170 LET NUMB = 3
1180 LET NUMR = 1
1190 FOR I = 1 TO NUMA
1200 FOR J = 1 TO NUMB
1210 READ F(I,J,l)
1220 NEXT J
1230 NEXT I
1240 REM
1250 REM COMPUTE ANOVA TABLE
1260 REM CALL SUBROUTINE TWAOVA
1270 GOSUB 2000
1280 PRINT" TABLE OF MEANS OF INPUT DATA"
1290 PRINT
1300 FOR I = 1 TO NUMA1
1310 FOR J = 1 TO NUMB
1320 PRINT M(I,J);
1330 NEXT J
1340 PRINT" ", M(I,NUMB1)
1350 IF I = NUMA THEN PRINT
1360 NEXT I
1370 PRINT
1380 PRINT" ANOVA TABLE"
1390 PRINT
The Subroutines 83

1400 PRINT II SOURCE D.F. SUM SQ MEAN SQII;


1410 PRINT II F-RATIO"
1420 PRINT
1430 PRINT II EFF. A II., C(l,l), C(l,2), C(1,3), C(1,4)
1440 PRINT II EFF. B II ,. C(2,1), C(2,2), C(2,3), C(2,4)
1450 PRINT II RESID. II., C(4,1), C(4,2), C(4,3)
1460 PRINT II TOTAL II., C(5,1), C(5,2)
1470 END

>RUN
TABLE OF MEANS OF INPUT DATA

55.2 59.6 48.8 54.5333


56.5 53.5 46.3 52.1
59.5 54 56.1 56.5333
58.4 53.3 43.7 51. 8
59.4 56.2 52.9 56.1667

57.8 55.32 49.56 54.2267

ANOVA TABLE

SOURCE D.F. SUM SQ MEAN SQ F-RATIO

EFF. A 4 58.7693 14.6923 1. 41288


EFF. B 2 178.709 89.3547 8.59276
RESID. 8 83.1907 10.3988
TOTAL 14 320.669

From tables F O•05 ,4,8 = 3.84 and FO.OS,2,S = 4.46. These values are to be com-
pared with the F-ratios of 1.41 and 8.59 respectively. Thus the effect due to the
operators (the B effect) is significant at the 5 per cent level and consequently
there is evidence of a real difference in their performances. The low value ofF
achieved for the machines (the A effect) provides little evidence that any differences
in performance can be attributed to them.

2. With Replication

Two lots of four brands of paint were examined in an accelerated life test. The
performance of the paints under three environmental conditions was examined
and the table overleaf constructed. The table shows the number of days the paint
samples survived the test. Construct an ANOVA table and use this to comment
on the performance of paints under various conditions.
84 Advanced BASIC SCientific Subroutines

Paint
Environment (effect B)
(effect A)

1 163 204 183


182 214 231
2 209 197 221
124 165 179
3 142 158 229
121 188 209
4 194 224 222
136 180 171

Paint Life with Environments

1000 REM SAMPLE PROGRAM: PTWAOVA2


1010 REM
1020 REM TWO-WAY ANOVA WITH REPLICATES
1030 REM
1040 REM ARRAY DIMENSIONS:
1050 DIM C(5,4)
1060 DIM F(4.3,2)
1070 DIM M(5,4)
1080 REM
1090 DATA 163, 182, 204, 214, 183, 231
1100 DATA 209, 124, 197, 165, 221, 179
1110 DATA 142, 121, 158, 188, 229, 209
1120 DATA 194, 136, 224, 180, 222, 171
1130 REM
1140 REM SET INITIAL VALUES AND READ INPUT DATA
1150 LET NUMA = 4
1160 LET NUMB = 3
1170 LET NUMR = 2
1180 FOR I = 1 TO NUMA
1190 FOR J = 1 TO NUMB
1200 FOR K = 1 TO NUMR
1210 READ F(I,J,K)
1220 NEXT K
1230 NEXT J
1240 NEXT I
1250 REM
1260 REM COMPUTE ANOVA TABLE
1270 REM CALL SUBROUTINE TWAOVA
1280 GOSUB 2000
1290 PRINT " TABLE OF MEANS OF INPUT DATA"
1300 PRINT
1310 FOR I = 1 TO NUMA1
1320 FOR J = 1 TO NUMB
1330 PRINT M(I,J);
The Subroutines 85

1340 NEXT J
1350 PRINT"" M(I,NUMB1)
1360 IF I = NUMA THEN PRINT
1370 NEXT I
1380 PRINT
1390 PRINT " ANOVA TABLE"
1400 PRINT
1410 PRINT "SOURCE D.F. SUM SO MEAN SO";
1420 PRINT " F-RATIO"
1430 PRINT
1440 PRINT " EFF. A "; C(l,l), C(1,2), C(1,3), C(1,4)
1450 PRINT " EFF. B "; C(2,1), C(2,2), C(2,3), C(2,4)
1460 PRINT " INTACT. "; C(3,1), C(3,2), C(3,3), C(3,4)
1470 PRINT " RESIO. "; C(4,1), C(4,2), C(4,3)
1480 PRINT "TOTAL "; C(5,1), C(5,2)
1490 END

>RUN
TABLE OF MEANS OF INPUT DATA

172.5 209 207 196.167


166.5 181 200 182.5
131. 5 173 219 174.5
165 202 196.5 187.833

158.875 191.25 205.625 185.25

ANOVA TABLE

SOURCE D.F. SUM SO MEAN SO F-RATIO

EFF. A 3 1493.83 497.944 0.533036


EFF. B 2 9174.25 4587.12 4.91039
INTACT. 6 2896.42 482.736 0.516756
RESID. 12 11210 934.167
TOTAL 23 24774.5

From tables F O•05 ,3,12 =3.49, F O•05 ,2,12 =3.88 andFo.05 ,6,12 =3.00. The
values of F for the interaction and paint effects are 0.52 and 0.53, consequently
there is no evidence to suggest that there is any real difference between the
general performance of the paints under the various environmental conditions.
The effect of the environment on paint life is likely to be real as the value for
F of 4.91 is significant at the 5 per cent level.

Notes

1. With some experimental data the residual (or unexplained variation) can
approach zero. To avoid interruption of the program under these conditions a
check for a low residual value is made. If the residual sum of squares is found to
86 Advanced BASIC Scientific Subroutines

be less than a factor of 105 smaller than the total sum of squares, the residual is
increased and a warning issued.
2. For this analysis the number of observations in each cell must be equal.
3. Scheffel (1959), Chatfield (1970), Davis and Goldsmith (1972) and Wonnacott
and Wonnacott (1981) are suggested for further reading.
The Subroutines 87

2.5 Linear Regression

MULTIPLE LINEAR REGRESSION

Subroutines: MLNRG1, MLNRG2, MLNRG3, MLNRG4

Description

This set of four principal subroutines may be used to fit a sample of data to a
curve of the form y = B 1 + B2X2 + ... + BkXk' The values of the coefficients B
are estimated by the method of least squares. In addition to determining the
regression coefficients, supporting information is computed, inclUding: corre-
lation coefficients, ANOYA table, standard error of the coefficients and residual
analysis.
Requires subroutines SOLUTN and MATDET for full analysis.

Method

A model of the formy =B1Xl +B2X2 + ... + BkXk + eis employed, where
are the regression coefficients; Xl is set to unity in all obser-
Bl ,B 2 , . . . ,B k
vations and B 1 is the constant term; X2 , X3, ... ,Xk are the independent
variables and y the dependent variable. The error term, e, is equal to the dif-
ference between the observed value of y and its predicted value. The system
of equations may be represented in matrix notation by
Y=XB+E

which is equivalent to

Xl2 XI3··. Xlk


X22 X23'" X2k

Xn 2 X n 3'" Xnk

where n is the number of sets of observations.


The set of least-squares estimates for B is given by
B = (XTX)-l XTy

These equations are sometimes referred to as the normal equations. Calling


all four principal subroutines will perform the full analysis. Partial analysis may
be conducted though MLNRG I, MLNRG2, MLNRG3 and MLNRG4 must be called
in order.
88 Advanced BASIC Scientific Subroutines

The purpose and action of these subroutines is described below.

Subroutine: MLNRGI

Description

Computes mean, variance, standard error and correlation matrix for each set of
variables. Also evaluates X T X.

Method

Array F( ) is used to store the input data. The first column of this array is gener-
ated by the subroutine, the other columns being filled from the driver program so
that information is contained in the following form:

XIZ X13'" Xlk Yl


Xn XZ3'" XZk Yz

XnZ X n 3'" Xnk Yn

The driver program sets NUMOBS equal to the number of sets of observations
and NUMINV equal to the number of independent variables (n and k - 1 respec-
tively in the preceding notation).
The transpose of F( ) is multiplied by F( ) and the result placed in array D( ).
D() contains X TX and XTy, and this information facilitates the calculation of
the summary statistics: mean
n
Xi= ~ xmdn
m=l

estimate ~f variance

and standard deviation si.


These results are stored in array H( ). The values of the dependent variable Y
are treated in the same manner as the independent variables x at this stage.
The correlation ofxj andxj (and similarly xi andy) are computed from

n
~
m=l
+)
xm;/n •
The Subroutines 89

The result of this computation for all variables is stored in array V( ).

Subroutine: MLNRG2

Description

Finds the inverse of X T X and estimates the values of the regression coefficients.

Method

xTx and XTYare copied from array D() into A() and the normal equations
XTXB = XTYare solved with the aid of subroutine SOLUTN (which in turn
calls subroutine MATDET). A() is expanded beyond the usual requirements of
SOLUTN by inserting an identity matrix between XTX and XTy so that (XTX)-l
may be extracted from A after execution and this is contained in rows and columns
1 to k. The values of the estimates of the coefficients are held in the first column
of array B( ).

Subroutine MLNRG3

Description

Computes the analysis of variance table, the standard error of estimate, the
standard error of the estimated coefficients and the multiple regression coefficient
R2.

Method

The ANOVA table is stored in array C().

Source of Degrees of Sum of Mean F-ratio


variation freedom squares square

Due to C(1, 1) = C(1,2)=B 2 sy2 + C(1, 3) = C(1,4)=


regression p-1 B3 sY3 +... +Bksyk
C(l, 2)/C(1, 1) C(1, 3)/C(2, 3)
Residual C(2, 1) = C(2, 2) = C(2, 3) =
n-p C(3, 2) - C(l, 2) C(2, 2)/C(2, 1)
Total C(3, 1) = C(3, 2) =
n-1 Syy

Analysis of Variance Table


90 Advanced BASIC Scientific Subroutines

where p = k - 1, number of independent variables, and


n n n
syi = ~ xmiYm - ~ xmi ~ Ym/ n
m=l m=l m=l

n n
Syy = ~ Y~ - ~ Ym/n
m=l m=l

The standard error of estimate a = VC(2, 3) and the multiple regression coef-
ficient is given by Rl = C(1, 2)/C(3, 2).
The standard errors of the estimated coefficients are calculated from
SE(B) = «(XTX)-l)al )1-
and placed in column 2 of array B( ).

Subroutine MLNRG4

Description

Performs residual analysis, computes predicted value of the dependent variable, the
residual and the standardised residual.

Method

The results of the residual analysis are stored in array R( ). The first column of R
contains the value of the dependent variable predicted from
y=Bl +BlXl + . .. +BkXk
for the values of x provided in the input data and the values of B estimated by
MLNRG2. Predicted and observed values are compared and their difference stored
in column 2 of R( ). The third column contains the standardised residual which is
the difference between observed and predicted values of Y divided by the standard
error of estimate, a.

Subroutine Listings

3000 REM MULTIPLE LINEAR REGRESSION


3010 REM
3020 REM SUBROUTINE: MLNRG1
3030 REM
3040 REM COMPUTES MEAN, VARIANCE, STANDARD ERROR
3050 REM }ND CORRELATION MATRIX FOR EACH SET OF VAR-
3060 REM IABLES. MLNRG1 MAY BE USED WITH SUBROUTINES
3070 REM MLNRG2 (WITH SOLUTN AND MATDET), MLNRG3 AND
3080 REM MLNRG4 TO SOLVE LINEAR REGRESSION EQUS OF
3090 REM THE FORM Y = XB + E FOR NUMOBS OBSERVATIONS
3100 REM AND NUMINV INDEPENDENT VARIABLES. AN ANOVA
The Subroutines 91

3110 REM TABLE IS PRODUCED AND AN EVALUATION OF


3120 REM RESIDUALS MADE.
3130 REM
3140 REM VARIABLES:
3150 REM INPUT:
3160 REM F() ..... COLS. 2 TO NUMINV+l CONTAIN VALUES
3170 REM OF THE INDEPENDENT VARIABLES AND
3180 REM NUMINV+2 THE DEPENDENT VARIABLE
3190 REM NUMINV .. NUMBER OF INDEPENDENT VARIABLES
3200 REM NUMOBS .. NUMBER OF SETS OF OBSERVATIONS
3210 REM OUTPUT:
3220 REM D( ) ..... CONTAINS F'F
3230 REM H() ..... ROW 1, MEANS OF VARIABLES
3240 REM ROW 2, THEIR STANDARD DEVIATIONS
3250 REM ROW. 3, VARIANCE OF VARIABLES
3260 REM ROWS 4,5 HOLD INTERMEDIATE RESULTS
3270 REM NUMINl .. NUMINV + 1
3280 REM NUMIN2 .. NUMINV + 2
3290 REM V() ..... CORRELATION MATRIX
3300 REM ROWS AND COLS. 1 TO NUMINV CONTAIN
3310 REM THE X CORRELATIONS. ROW AND COLUMN
3320 REM NUMINV+1 HOLD THE XY CORRELATIONS
3330 REM LOCAL: ... P, Q, R, VI
3340 REM ARRAY DIMENSIONS:
3350 REM F() ..... (NUMOBS,NUMINV + 2)
3360 REM D() ..... (NUMINV + 2,NUMINV + 2)
3370 REM H() ..... (5,NUMINV + 2)
3380 REM V() ..... (NUMINV + I,NUMINV + 1)
3390 REM
3400 REM CHECK NUMOBS AND NUMINV
3410 LET NUMINI = NUMINV + 1
3420 LET NUMIN2 = NUMINV + 2
3430 IF NUMOBS < NUMIN2 OR NUMINV < 1 THEN GOTO 3860
3440 REM
3450 REM SET FIRST COLUMN OF INFORMATION MATRIX F
3460 FOR P = 1 TO NUMOBS
3470 LET F(P,I) = 1
3480 NEXT P
3490 REM
3500 REM FIND LOWER DIAGONAL OF F'F AND PLACE IN D
3510 FOR P = 1 TO NUMIN2
3520 FOR Q = P TO NUMIN2
3530 LET D(Q,P) = 0
3540 FOR R = 1 TO NUMOBS
3550 LET D(Q,P) = D(Q,P) + F(R,Q)*F(R,P)
3560 NEXT R
3570 NEXT Q
3580 NEXT P
3590 REM
3600 REM COMPLETE MATRIX D, WHICH CONTAINS F'F.
3610 REM ROWS AND COLUMNS I,NUMINI CONTAIN X'X
3620 FOR P = 2 TO NUMIN2
3630 FOR Q = 1 TO P - 1
3640 LET D(Q,P) = D(P,Q)
3650 NEXT Q
92 Advanced BASIC Scientific Subroutines

3660 NEXT P
3670 REM
3680 REM CALCULATE MEAN, VARIANCE AND STANDARD ERROR
3690 FOR P = 1 TO NUMIN2
3700 LET H(l,P) D(l,P)/NUMOBS
3710 LET H(4,P) D(P,P) - D(l,P)*H(l,P)
3720 LET H(5,P) SQR(H(4,P))
3730 LET H(3,P) H(4,P)/(NUMOBS- 1)
3740 LET H(2,P) SQR(H(3,P))
3750 NEXT P
3760 REM
3770 REM COMPUTE CORRELATION MATRIX
3780 FOR P = 2 TO NUMIN2
3790 FOR Q = 2 TO NUMIN2
3800 IF H(5,Q) = 0 THEN GOTO 3910
3810 LET V1 = D(P,Q) - H(l,P)*D(l,Q)
3820 LET V(P-1,Q-1) = V1/(H(5,P)*H(5,Q))
3830 NEXT Q
3840 NEXT P
3850 RETURN
3860 REM
3870 PRINT " NUMBER OF OBSERVATIONS AND/OR VARIABLES";
3880 PRINT " UNSUITABLE FOR REGRESSION ANALYSIS."
3890 PRINT " NUMOBS = "; NUMOBS; " NUMINV = "; NUMINV
3900 END
3910 REM
3920 PRINT" TOO LITTLE INFO ON SE OF VARIABLE "; Q
3930 END
4000 REM SUBROUTINE: MLNRG2
4010 REM
4020 REM COMPUTES B VALUES BY SOLVING NORMAL EQUS AND
4030 REM FINDS INVERSE OF X'X (SEE TEXT) WITH THE AID
4040 REM OF SUBROUTINE SOLUTN. REQUIRES THE INPUT AND
4050 REM OUTPUT OF SUBROUTINE MLNRG1.
4060 REM
4070 REM VARIABLES:
4080 REM OUTPUT:
4090 REM A() ..... CONTAINS INV. OF X'X IN ROWS
4100 REM AND COLS (1,NUMINV+1)
4110 REM B() ..... COL. 1 CONTAINS B COEFFICIENTS
4120 REM LOCAL: ... MCOL, MDET, ODR, P, Q, R, W()
4130 REM ARRAY DIMENSIONS:
4140 REM A() ..... (NUMINV + 1,2*NUMINV + 3)
4150 REM B() ..... (NUMINV + 1,2)
4160 REM W() ..... (NUMINV + 2 )
4170 REM
4180 REM COPY X'X, IDENTITY MATRIX AND X'Y INTO A()
4190 FOR P = 1 TO NUMIN1
4200 FOR Q = 1 TO NUMIN1
4210 LET A(P,Q) = D(P,Q)
4220 NEXT Q
4230 FOR Q = NUMIN2 TO 2*NUMIN1
4240 LET A(P,Q) = 0
4250 NEXT Q
The Subroutines 93

4260 LET A(P,NUMIN1 + P) = 1


4270 LET A(P,2*NUMIN1 + 1) D(P,NUMIN2)
4280 NEXT P
4290 LET ODR = NUMIN1
4300 LET MCOL = 2*ODR + 1
4310 REM
4320 REM SOLVE NORMAL EQUATIONS AND COMPUTE B VALUES
4330 REM CALL SUBROUTINE SOLUTN
4340 GOSUB 7000
4350 FOR P = 1 TO NUMIN1
4360 LET B(P,l) = A(P,NUMIN2)
4370 NEXT P
4380 RETURN
5000 REM SUBROUTINE: MLNRG3
5010 REM
5020 REM COMPUTES ANOVA TABLE, SE OF ESTIMATE,
5030 REM R-SQUARED AND SE OF B COEFFICIENTS. REQUIRES
5040 REM INPUT AND OUTPUT OF MLNRG1 AND MLNRG2
5050 REM
5060 REM VARIABLES:
5070 REM OUTPUT:
5080 REM B ( ) ..... COL. 2 - SE OF B ESTIMATES
5090 REM C( ) ..... COL.1 - DEGRESS OF FREEDOM
5100 REM COL.2 - SUM OF SQUARES
5110 REM COL.3 - MEAN SQUARE
5120 REM COL.4 - F-RATIO
5130 REM ROW 1 - DUE TO REGRESSION
5140 REM ROW 2 - RESIDUAL
5150 REM ROW 3 - TOTAL
5160 REM RSQRED .. R-SQUARED
5170 REM SEOFET .. STANDARD ERROR OF ESTIMATE
5180 REM LOCAL: ... P, V1
5190 REM ARRAY DIMENSIONS:
5200 REM B() .... (NUMINV + 1,2)
5210 REM C() .... (3,4)
5220 REM
5230 REM DETERMINE DEGREES OF FREEDOM
5240 LET C(l,l) NUMINV
5250 LET C(2,1) = NUMOBS - 1 - NUMINV
5260 LET C(3,1) = NUMOBS - 1
5270 REM
5280 REM COMPUTE SUM OF SQUARES
5290 LET C(1,2) = 0
5300 FOR P = 1 TO NUMINV
5310 LET V1 = D(l,P + 1)*H(1,NUMIN2)
5320 LET V1 = B(P + 1,1)*(D(P + 1,NUMIN2) - V1)
5330 LET C(1,2) = C(1,2) + V1
5340 NEXT P
5350 LET V1 = D(1,NUMIN2)*H(1,NUMIN2)
5360 LET C(3,2) = D(NUMIN2, NUMIN2) - V1
5370 LET C(2,2) = C(3,2) - C(1,2)
5380 REM
5390 REM CHECK FOR POSSIBLE ROUNDING ERROR
5400 IF C(2,2)/C(3,2) > 1E-6 THEN GOTO 5450
94 Advanced BASIC Scientific Subroutines

5410 PRINT" NOTE: VERY CLOSE FIT, RESIDUAL";


5420 PRINT" MEAN SQUARE LESS THAN lE-6*TOTAL."
5430 PRINT" TRUE ERROR TERMS LESS THAN COMPUTED."
5440 LET C(2,2) = 1E-6*C(3,2)
5450 REM
5460 REM COMPUTE MEAN SQUARE AND F RATIO
5470 LET C(1,3) C(1,2)/C(1,l)
5480 LET C(2,3) C(2,2)/C(2,1)
5490 LET C( 1, 4) C(1,3)/C(2,3)
5500 LET SEOFET SQR(C(2,3))
5510 LET RSQRED C(1,2)/C(3,2)
5520 REM
5530 REM COMPUTE SE OF B'S AND PLACE IN B(*,2)
5540 FOR P = 1 TO NUMINI
5550 LET B(P,2) = SQR(C(2,3)*A(P,P))
5560 NEXT P
5570 RETURN
6000 REM SUBROUTINE: MLNRG4
6010 REM
6020 REM COMPUTES PREDICTED VALUE, RESIDUAL AND
6030 REM STANDARDISED RESIDUAL. REQUIRES INPUT AND
6040 REM OUTPUT OF MLNRGl, MLNRG2 AND MLNRG3
6050 REM
6060 REM VARIABLES:
6070 REM OUTPUT:
6080 REM R() ..... COL.1 - PREDICTED VALUE
6090 REM COL.2 - RESIDUAL
6100 REM COL.3 - STANDARDISED RESIDUAL
6110 REM LOCAL: ... P, Q
6120 REM ARRAY DIMENSIONS:
6130 REM R() ...... (NUMOBS,3)
6140 REM
6150 REM CALCULATE PREDICTED VALUE OF Y, RESIDUAL AND
6160 REM STANDARDISED RESIDUAL AND PLACE IN R(*,I),
6170 REM R(*,2) AND R(*,3) RESPECTIVELY
6180 FOR P = 1 TO NUMOBS
6190 LET R ( P , 1) = 0
6200 FOR Q = 1 TO NUMINI
6210 LET R(P,I) = R(P,l) + B(Q,I)*F(P,Q)
6220 NEXT Q
6230 LET R(P,2) F(P,NUMIN2) - R(P,I)
6240 LET R(P,3) = R(P,2)/SEOFET
6250 NEXT P
6260 RETURN
The Subroutines 95

Sample Program

Fit the equationy = Bl + B2X2 + B3X3 + B4X4 to the data presented in the table
below. Generate an ANOVA table and comment on the goodness of fit.

Y X2 X3 X4

0.11 1 1.0 20.0


0.12 1 2.0 21.0
0.13 2 3.0 16.0
0.14 2 1.0 31.0
0.15 3 2.0 27.0
0.16 3 3.0 23.0
0.17 4 4.0 24.0
0.18 4 -1.0 49.0
0.19 5 -2.0 56.0
0.20 5 -3.0 66.0
0.21 6 -4.0 72.5
0.22 6 0.0 54.5
0.23 7 5.1 31.5
0.24 7 1.0 58.0
0.25 8 -1.1 67.5

1000 REM SAMPLE PROGRAM: PMLNREG


1010 REM
1020 REM PERFORMS LINEAR REGRESSION ANALYSIS
1030 REM
1040 REM ARRAY DIMENSIONS:
1050 DIM A(4,9)
1060 DIM B(4,2)
1070 DIM C(3,4)
1080 DIM D(5,5)
1090 DIM F(15,5)
1100 DIM H(5,5)
1110 DIM R(15,3)
1120 DIM V(4,4)
1130 DIM W(5)
1140 REM
115'0 DATA .11, .12, .13, .14, .15, .16, .17, .18
1160 DATA .19, .20, .21, .22, .23, .24, .25
1170 DATA 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8
1180 DATA 1, 2, 3, 1, 2, 3, 4, -I, -2, -3, -4, 0, 5.1
1190 DATA 1, -1.1, 20, 21, 16, 31, 27, 23, 24, 49, 56
1200 DATA 66, 72.5, 54.5, 31.5, 58, 67.5
1210 REM
1220 REM SET INITIAL VALUES AND READ AND PRINT DATA
1230 LET NUMOBS 15
1240 LET NUMINV = 3
96 Advanced BASIC Scientific Subroutines

1250 FOR 1= 2 TO NUMINV + 2


1260 FOR J = 1 TO NUMOBS
1270 READ F(J,I)
1280 NEXT J
1290 NEXT I
1300 PRINT " INPUT DATA"
1310 FOR I = 1 TO NUMOBS
1320 FOR J = 2 TO NUMINV + 2
1330 PRINT F(I,J);
1340 NEXT J
1350 PRINT
1360 NEXT I
1370 PRINT
1380 PRINT" NO. OF OBSERVATIONS = "; NUMOBS
1390 PRINT" NO. OF INDEPENDENT VARIABLES = "; NUMINV
1400 REM
1410 REM COMPUTE MEAN, VARIANCE, STANDARD ERROR AND
1420 REM CORRELATION MATRIX. CALL SUBROUTINE MLNRG1
1430 GOSUB 3000
1440 PRINT
1450 PRINT" MEAN, STANDARD DEVIATION AND VARIANCE"
1460 FOR I = 1 TO 3
1470 FOR J = 2 TO NUMIN2
1480 PRINT H(I,J)j
1490 NEXT J
1500 PRINT
1510 NEXT I
1520 PRINT
1530 PRINT " CORRELATION MATRIX"
1540 FOR I = 1 TO NUMIN1
1550 FOR J = I TO NUMINI
1560 PRINT V(I,J);
1570 NEXT J
1580 PRINT
1590 NEXT I
1600 REM
1610 REM CALCULATE THE VALUES OF THE B COEFFICIENTS
1620 REM CALL SUBROUTINE MLNRG2
1630 GOSUB 4000
1640 REM
1650 REM COMPUTE ANOVA TABLE, SE OF ESTIMATE,
1660 REM R-SQUARED AND SE OF B COEFFICIENTS
1670 REM CALL SUBROUTINE MLNRG3
1680 GOSUB 5000
1690 PRINT
1700 PRINT " ANALYSIS OF VARIANCE TABLE"
1710 PRINT
1720 PRINT" SOURCE D.F. SUM SQ ", .
1730 PRINT "MEAN SQ F-RATIO"
1740 PRINT" REGRESSION "; C(I,l), C(1,2), C(1,3);
1750 PRINT C(l,4)
1760 PRINT " RESIDUAL "; C(2,l), C(2,2), C(2,3)
1770 PRINT " TOTAL "; C(3,l), C(3,2)
1780 PRINT
1790 PRINT" STANDARD ERROR OF ESTIMATE = "; SEOFET
The Subroutines 97

1800 PRINT " R-SQUARED = If; RSQRED


1810 PRINT
1820 PRINT " COEFFICIENTS B AND THEIR STANDARD ERRORS"
1830 PRINT
1840 FOR I 1 TO 2
1850 FOR J = 1 TO NUMIN1
1860 PRINT B(J,I);
1870 NEXT J
1880 PRINT
1890 NEXT I
1900 REM
1910 REM PERFORM ANALYSIS OF RESIDUALS
1920 REM CALL SUBROUTINE MLNRG4
1930 GOSUB 6000
1940 PRINT
1950 PRINT " ANALYSIS OF RESIDUALS"
1960 PRINT
1970 PRINT " OBS NO. OBS Y PRED.Y";
1980 PRINT " RESIDUAL STAND. RESID."
1990 FOR I 1 TO NUMOBS
2000 PRINT I, F(I,NUMIN2), R(I,l), R(I,2), R (1,3)
2010 NEXT I
2020 END
>RUN
INPUT DATA
0.11 1 1 20
0.12 1 2 21
0.13 2 3 16
0.14 2 1 31
0.15 3 2 27
0.16 3 3 23
0.17 4 4 24
0.18 4 -1 49
0.19 5 -2 56
0.2 5 -3 66
0.21 6 -4 72.5
0.22 6 0 54.5
0.23 7 5.1 31.5
0.24 7 1 58
0.25 8 -1.1 67.5
NO. OF OBSERVATIONS 15
NO. OF INDEPENDENT VARIABLES = 3

MEAN, STANDARD DEVIATION AND VARIANCE


0.18 4.267 0.7333 41.13
4.472E-2 2.251 2.593 19.9
2E-3 5.067 6.725 396.1
CORRELATION MATRIX
1 0.9934 -0.3092 0.7869
0.9934 1 -0.2941 0.7701
-0.3092 -0.2941 1 -0.8264
0.7869 0.7701 -0.8264 1
98 Advanced BASIC Scientific Subroutines

ANALYSIS OF VARIANCE TABLE

SOURCE D.F. SUM SQ MEAN SQ F-RATIO


REGRESSION 3 5522 1841 892.7
RESIDUAL 11 22.68 2.062
TOTAL 14 5545

STANDARD ERROR OF ESTIMATE 1. 436


R-SQUARED 0.9959

COEFFICIENTS B AND THEIR STANDARD ERRORS

-12.74 371 -2.181 -4.92


7.36 75.73 1. 497 0.1567

ANALYSIS OF RESIDUALS

OBS NO. OBS Y PRED.Y RESIDUAL STAND. RESID.


1 20 20.97 -0.9746 -0.6787
2 21 19.76 1. 235 0.8603
3 16 16.37 -0.374 -0.2605
4 31 29.92 1. 076 0.7493
5 27 26.53 0.4666 0.3249
6 23 25.32 -2.324 -1. 618
7 24 21. 93 2.067 1. 44
8 49 50.24 -1.243 -0.8655
9 56 56.69 -0.6921 -0.482
10 66 65.32 0.6778 0.4721
11 72.5 71. 77 0.7285 0.5074
12 54.5 55.8 -1. 302 -0.9065
13 31. 5 32.24 -0.7392 -0.5148
14 58 56.12 1. 879 1. 308
15 67.5 67.98 -0.4824 -0.3359

The equation
y = 12.74 + 37lxz - 2.l8lx3 - 4.92x4
has been determined by least squares regression.
Examination of the standard errors shows that the coefficients B z and B4 lie
within two standard errors of zero and consequently Xz and X4 are important in
the determination of y. The value of x 3 however is less clear and further analysis
may be appropriate to judge whether or not this parameter should be retained.
Overall the model provides a very close fit to the data:
(a) The residual mean square is low.
(b) The multiple regression coefficient R Z indicates a fit of 99.6 per cent.
(c) Observed and predicted values are close.
The Subroutines 99

Notes

1. Most practical regression problems produce normal equations that are well
behaved, however certain properties of the input data could cause execution of
the program to be disrupted and some error detection is included within the sub-
routines to assist with diagnosis. Interruption will occur if the input data contain
insufficient information to permit the solution of the normal equations or esti-
mation of the variance of the data. Rounding errors may cause disruption in the
case of ill-conditioned equations. If ill-conditioning is detected a warning is printed
by subroutine MATDET though interruption of the program will only occur if
gross inaccuracy causes subsequent failure (such as square-root error). Ill-
conditioning may cause values of the coefficients B to be determined which fit
the data well and yet which may be widely different from true values.
2. The computed value of residual may be effectively zero under some circum-
stances. In such cases a small but finite value for error variance is substituted, a
warning message is issued and computation continued.
3. Scheffe (1959), Chatfield (1970), Davis and Goldsmith (1972), Miller (1981)
and Wonnacott and Wonnacott, (1981) are suggested for further reading.
100 Advanced BASIC Scientific Subroutines

POLYNOMIAL REGRESSION

Subroutine: POLYRG

Description

Computes the least squares estimates of the coefficients in relationships of the


formy = Bl + Blz + B3Z2 + ... + Bkz k - l for a number of observations. The full
output provided by the set of subroutines on multiple linear regression and des-
cribed in the previous section is available.
Requires subroutines MLNRG1, MLNRG2, SOLUTN, MATDET, MLNRG3 and
MLNRG4 for full analysis.

Method

Fitting the polynomial relationship is exactly the same as fitting multiple regression
with Z, Zl , Z3, ... ,zk-l replacing the values of the independent variables Xl,
X3, X4, •.. ,xk-l for a polynomial of degree k - 1
The subroutine POLYREG transforms the input data so that they are in a form
suitable for MLNRG 1. The value for z is placed in the first column of F( ) and the
value for y in the second. The degree of the polynomial is selected and POLYRG
generates the higher orders of z for each observation.

Subroutine Listing

2000 REM POLYNOMIAL REGRESSION


2010 REM
2020 REM SUBROUTINE: POLYRG
2030 REM
2040 REM SOLVES REGRESSION EQUATIONS OF THE FORM
2050 REM Y = B1 + B2*Z + B3*Z~2 + B4*Z~3 + • • •
2060 REM REQUIRES SUBROUTINES MLNRG1, MLNRG2, SOLUTN,
2070 REM MATDET, MLNRG3 AND MLNRG4 FOR FULL ANALYSIS.
2080 REM TO DETERMINE ARRAY SIZE USE NUMINV = DGREE.
2090 REM
2100 REM VARIABLES:
2110 REM INPUT:
2120 REM DGREE ... DEGREE OF POLYNOMIAL TO BE FIT'I'ED
2130 REM F() ..... COL.1 CONTAINS INDEPENDENT VARIABLE
2140 REM COL.2 CONTAINS DEPENDENT VARIABLE
2150 REM NUMOBS .• NUMBER OF SETS OF OBSERVATIONS
2160 REM OUTPUT:
2170 REM F() ..... COLS.2 TO DGREE + 1 HOLD ASCENDING
2180 REM POWERS OF THE INDEPENDENT VARIABLE
2190 REM FROM 1 TO DGREE. COLUMN DGREE + 2
2200 REM CONTAINS THE DEPENDENT VARIABLE
2210 REM NUMINV .. DGREE
2220 REM LOCAL: ... P, Q
The Subroutines 101

2230 REM ARRAY DIMENSIONS:


2240 REM F() ..... (NUMOBS,DGREE + 2)
2250 REM
2260 REM CHECK DEGREE AND NUMOBS
2270 REM
2280 LET NUMINV DGREE
2290 IF DGREE < 1 OR DGREE > NUMOBS - 1 THEN GOTO 2410
2300 REM
2310 REM ORDER DATA IN F() FOR MLNRG1
2320 FOR P = 1 TO NUMOBS
2330 LET F(P,DGREE + 2) = F(P,2)
2340 LET F(P,2) = F(P,1)
2350 LET F(P,l) = 1
2360 FOR Q = 1 TO DGREE
2370 LET F(P,Q + 1) = F(P,2)*F(P,Q)
2380 NEXT Q
2390 NEXT P
2400 RETURN
2410 REM
2420 PRINT " DEGREE OR NO. OF OBSERVATIONS INAPPROPRIATE"
2430 PRINT" DEGREE = "; DGREE; " NO. OF OBS. = "; NUMOBS
2440 END

Sample Program

Use regression techniques to fit a polynomial of the formy =B 1 + B 2 z + B3Z2 +


B4Z3 to the data below. Assess the goodness of fit and compare observed and
predicted values of y.
Z -2 -1 0 1 2 3 4 5 6
y -22 -6 2 0 2 6 26 60 122

1000 REM SAMPLE PROGRAM: PPOLYRG


1010 REM
1020 REM PERFORMS POLYNOMIAL REGRESSION ANALYSIS
1030 REM
1040 REM ARRAY DIMENSIONS:
1050 DIM A( 4,9 )
1060 DIM B(4,2)
1070 DIM C(3,4)
1080 DIM 0(5,5)
1090 DIM F(9,5)
1100 DIM H(5,5)
1110 DIM R(9,3)
1120 DIM V( 4,4 )
1130 DIM W(5)
1140 REM
1150 DATA -2, -22, -1, -6, 0, 2, 1, 0, 2, 2, 3, 6, 4
1160 DATA 26, 5, 60, 6, 122
1170 REM
1180 REM SET INITIAL VALUES. AND READ INPUT DATA
102 Advanced BASIC Scientific Subroutines

1190 LET NUMOBS '" 9


1200 LET DGREE = 3
1210 FOR I = 1 TO NUMOBS
1220 READ F(I,l), F(I,2)
1230 NEXT I
1240 REM
1250 REM PERFORM REGRESSION ANALYSIS
1260 REM CALL POLYRG, MLNRG1, MLNRG2, MLNRG3, MLNRG4
1270 GOSUB 2000
1280 GOSUB 3000
1290 GOSUB 4000
1300 GOSUB 5000
1310 GOSUB 6000
1320 PRINT" NUMBER OF OBSERVATIONS = "; NUMOBS
1330 PRINT" DEGREE fl; DGREE
1340 PRINT
1350 PRINT " COEFFICIENTS B AND THEIR STANDARD ERRORS"
1360 FOR I = 1 TO 2
1370 FOR J = 1 TO DGREE + 1
1380 PRINT B(J,I);
1390 NEXT J
1400 PRINT
1410 NEXT I
1420 PRINT
1430 PRINT" STANDARD ERROR OF ESTIMATE = "; SEOFET
1440 PRINT" R-SQUARED "; RSQRED
1450 PRINT
1460 PRINT " PREDICTED VALUES"
1470 PRINT
1480 PRINT " OBS NO. z OBS Y PRED. Y "
1490 FOR l I T O NUMOBS
1500 PRINT I, F(I,2), F(I,DGREE + 2), R(I,l)
1510 NEXT I
1520 END

>RUN
NUMBER OF OBSERVATIONS = 9
DEGREE 3

COEFFICIENTS B AND THEIR STANDARD ERRORS


0.9957 1.827 -2.957 1
0.7859 0.3378 0.2177 3.415E-2

STANDARD ERROR OF ESTIMATE 1.289


R-SQUARED = 0.9995

PREDICTED VALUES

OBS NO. Z OBS Y PRED. Y


1 -2 -22 -22.48
2 -1 -6 -4.788
3 0 2 0.9957
4 1 0 0.8658
5 2 2 0.8225
The Subroutines 103

6 3 6 6.866
7 4 26 25
8 5 60 61. 21
9 6 122 121. 5

The polynomial
y = 0.996 + 1.83z - 2.96z 2 + Z3
is found to fit the data. The coefficients of Z, Z2 and Z3 are all significant. The
value of R 2 indicates a very close fit overall though for values of y predicted near
zero the fit may be considered inadequate. Methods of improving the fit in this
region could include the fitting of a higher-order polynomial or increasing the
number of data points in this area.

Notes

1. Fitting a polynomial of degree k - 1 involves arithmetic operations that call


for the independent variable z to be raised to the power of 2(k - 1). The sub-
routine SOLUTN has been designed so as to reduce the effect of round-off errors,
nevertheless significant errors from this source will occur when fitting a polynomial
of high degree. These errors in turn may cause program interruption by, for
example, producing negative values of variance of estimated coefficients and
consequent square-root error message. When using a machine working with a
precision of eight significant figures, caution should be exercised when fitting
polynomials of degree higher than 4.
2. The techniques used for POLYRG may also be used to solve other regression
problems in which the coefficients to be estimated can be transformed to linear
form. For example
1
V= Co + Cl lnI + C2 [2 + C3 !
may be fitted by appropriate substitution in the set of multiple linear regression
subroutines. Substituting In! for X2, rt for X3, I for X4 and V for y will result in
Bl being an estimate ofCo,B2 ofC1 ,B 3 ofC2 andB 4 ofC3 •
3. Miller (1981) should prove helpful on other linear regressions; ScheffEl (1959),
Chatfield (1970), Davis and Goldsmith (1972) and Wonnacott and Wonnacott
(1981) are also suggested for further reading.
104 Advanced BASIC Scientific Subroutines

2.6 Matrix Operations

MATRIX ADDITION, SUBTRACTION, TRANSPOSITION, MULTIPLICATION


BY A CONSTANT, MULTIPLICATION OF TWO MATRICES, READING A
MATRIX FROM A DATA STATEMENT AND PRINTING A MATRIX

Subroutines: MATADD, MATSBT, MATTRN, MATCNT, MATMUL, MATRED,


MATWRT

Description

Performs addition, subtraction and multiplication of two matrices; multiplication


of a matrix by a constant; transposition of a matrix; reads input matrix and
prints output matrix.

Method

1. Addition. If A and B are two matrices of the same order with elements of
atj and b ij respectively, then their sum A + B is given by the resultant matrix C
with elements Cji =ajj + b j/ . C is of the same order asA and B.
2. Subtraction. Similar to addition but with C =A - B where cli =ajj - b ij .
3. Multiplication by a constant. If a matrix A with element ail is multiplied by
a constant k, the resultant matrix is Cwith element Cti = k.aii'
4. Transpose of a matrix. This is a matrix with rows and columns interchanged.
If C = A T then element aij in A becomes equal to element cii in C.
5. Multiplication of two matrices. Two matrices can be multiplied if they are
compatible; that is, if the number of columns of the first matrix is equal to the
number of rows of the second. If A is of order m x nand B is of order n x p,
then the product C = A *B is of order m x p with elements
n
cii = 1: aik·bkj
k=l

In the subroutines MATADD and MATSBT the matrices A andB are stored in
two-dimensional arrays A() and B() respectively. The resultant matrix Cis
stored in the array A( ) and over-writes the previous matrix A. This facilitates
further mathematical operations. Likewise in the subroutines MATCNT and
MATTRN the input matrix A and the resultant matrix C are stored in the array
A(). However, in the subroutine MATMUL the two matrices to be multiplied
are stored in the arrays A( ) and B( ) and the resultant matrix is stored in the
array C(). Care must be taken in dimensioning these arrays correctly. The
minimum allowable dimensions depend on the operations carried out. If p is
equal to the maximum row or column size of any array acted upon by the
subroutine, then the choice of dimension (p, p) for arrays A(), B() and C()
will prove satisfactory.
The Subroutines 105

The subroutine MATRED is written to read input matrices A and B via the
DATA statement from the main program. The selection is implemented by
setting the input variable RED$ equal to 'A' to read matrix A or 'B' to read
matrixB.
The subroutine MATWRT is written to print matricesA,B or C. The input
variable WRT$ is set to either' A' to write matrix A, 'B' to write matrix B or
'C' to write matrix C.

Subroutine Listing

2000 REM MATRIX ADDITION


2010 REM
2020 REM SUBROUTINE: MATADD
2030 REM
2040 REM ADDS TWO MATRICES. A BECOMES A + B
2050 REM
2060 REM VARIABLES:
2070 REM INPUT:
2080 REM A() •.... INPUT MATRIX A
2090 REM ACOL .... NUMBER OF COLUMNS IN A()
2100 REM AROW .... NUMBER OF ROWS IN A( )
2110 REM B() ..... INPUT MATRIX B()
2120 REM BCOL .... NUMBER OF COLUMNS IN B
2130 REM BROW .... NUMBER OF ROWS IN B
2140 REM OUTPUT:
2150 REM A() ..... RESULT MATRIX
2160 REM LOCAL .... P, Q
2170 REM ARRAY DIMENSIONS:
2180 REM A() ..... (AROW,ACOL)
2190 REM B() ..... (BROW,BCOL)
2200 REM
2210 IF AROW <> BROW OR ACOL <> BCOL THEN GOTO 2280
2220 FOR P= 1 TO AROW
2230 FOR a = 1 TO ACOL
2240 LET A(P,O) = A(P,O) + B(P,O)
2250 NEXT a
2260 NEXT P
2270 RETURN
2280 REM
2290 PRINT " INCOMPATIBLE MATRICES IN SUB. MATADD"
2300 END
3000 REM MATRIX SUBTRACTION
3010 REM
3020 REM SUBROUTINE: MATSBT
3030 REM
3040 REM SUBTRACTS TWO MATRICES. A BECOMES A - B
3050 REM
3060 REM VARIABLES:
3070 REM INPUT:
3080 REM A() ..... INPUT MATRIX A
3090 REM ACOL .... NUMBER OF COLUMNS IN A()
3100 REM AROW .... NUMBER OF ROWS IN A( )
106 Advanced BASIC Scientific Subroutines

3110 REM B() ..... INPUT MATRIX B()


3120 REM BCOL .... NUMBER OF COLUMNS IN B()
3130 REM BROW .... NUMBER OF ROWS IN B()
3140 REM OUTPUT:
3150 REM A() ..... RESULT MATRIX
3160 REM LOCAL: ... P, Q
3170 REM ARRAY DIMENSIONS:
3180 REM A() ..... (AROW,ACOL)
3190 REM B() ..... (BROW,BCOL)
3200 REM
3210 IF AROW <> BROW OR ACOL <> BCOL THEN GOTO 3280
3220 FOR P= 1 TO AROW
3230 FOR Q = 1 TO ACOL
3240 LET A(P,Q) = A(P,Q) - B(P,Q)
3250 NEXT Q
3260 NEXT P
3270 RETURN
3280 REM
3290 PRINT" INCOMPATIBLE MATRICES IN SUB. MATSBT"
3300 END
4000 REM MATRIX TRANSPOSITION
4010 REM
4020 REM SUBROUTINE: MATTRN
4030 REM
4040 REM TRANSPOSES A MATRIX. A BECOMES A TRANSPOSED
4050 REM
4060 REM VARIABLES:
4070 REM INPUT:
4080 REM A() ..... INPUT MATRIX
4090 REM ACOL .... NUMBER OF COLUMNS IN A()
4100 REM AROW .... NUMBER OF ROWS IN A()
4110 REM OUTPUT:
4120 REM A() ..... RESULT MATRIX
4130 REM LOCAL .... C(), P, Q
4140 REM ARRAY DIMENSIONS:
4150 REM A(),C().(N,N) WHERE N IS THE GREATER
4160 REM OF ACOL OR AROW
4170 REM
4180 FOR P = 1 TO AROW
4190 FOR Q = 1 TO ACOL
4200 LET C(Q,P) A(P,Q)
4210 LET A(P,Q) = 0
4220 NEXT Q
4230 NEXT P
4240 FOR P = 1 TO ACOL
4250 FOR Q = 1 TO AROW
4260 LET A(P,Q) = C(P,Q)
4270 NEXT Q
4280 NEXT P
4290 RETURN
5000 REM MATRIX MULTIPLICATION BY A CONSTANT
5010 REM
5020 REM SUBROUTINE: MATCNT
5030 REM
The Subroutines 107

5040 REM MULTIPLIES BY A CONSTANT. A BECOMES CONST*A


5050 REM
5060 REM VARIABLES:
5070 REM INPUT:
5080 REM A() ..... INPUT MATRIX
5090 REM ACOL .... NUMBER OF COLUMNS IN A
5100 REM AROW .... NUMBER OF ROWS IN A
5110 REM CONST ... MULTIPLICATION CONSTANT
5120 REM OUTPUT:
5130 REM A() ..... RESULT MATRIX
5140 REM LOCAL: ... P, Q
5150 REM ARRAY DIMENSIONS:
5160 REM A() ..... (AROW,ACOL)
5170 REM
5180 FOR P= 1 TO AROW
5190 FOR Q = 1 TO ACOL
5200 LET A(P,Q) = CONST*A(P,Q)
5210 NEXT Q
5220 NEXT P
5230 RETURN
6000 REM MATRIX MULTIPLICATION
6010 REM
6020 REM SUBROUTINE: MATMUL
6030 REM
6040 REM MULTIPLIES TWO MATRICES. C BECOMES A*B
6050 REM
6060 REM VARIABLES:
6070 REM INPUT:
6080 REM A() ..... INPUT MATRIX A
6090 REM ACOL .... NUMBER OF COLUMNS IN A()
6100 REM AROW .... NUMBER OF ROWS IN A( )
6110 REM B() ..... INPUT MATRIX B()
6120 REM BCOL .... NUMBER OF COLUMNS IN B()
6130 REM BROW .... NUMBER OF ROWS IN B( )
6140 REM OUTPUT:
6150 REM C() ..... RESULT MATRIX
6160 REM LOCAL: ... P, Q, R
6170 REM ARRAY DIMENSIONS:
6180 REM A() ..... (AROW,ACOL)
6190 REM B() ..... (BROW,BCOL)
6200 REM C() ..... (AROW,BCOL)
6210 REM
6220 IF ACOL <> BROW THEN GO TO 6320
G230 FOR P= 1 TO ACOL
6240 FOR Q = 1 TO BCOL
6250 LET C(P,Q) = 0
6260 FOR R = 1 TO ACOL
6270 LET C(P,Q) = C(P,Q) + A(P,R)*B(R,Q)
6280 NEXT R
6290 NEXT Q
6300 NEXT P
6310 RETURN
6320 REM
6330 PRINT" INCOMPATIBLE MATRICES IN SUB. MATMUL"
108 Advanced BASIC Scientific Subroutines

6340 END
7000 REM READ IN TWO MATRICES
7010 REM
7020 REM SUBROUTINE: MATRED
7030 REM
7040 REM READS MATRICES A AND B FROM A DATA STATEMENT
7050 REM
7060 REM VARIABLES:
7070 REM INPUT:
7080 REM A() •.... INPUT MATRIX A
7090 REM ACOL .... NUMBER OF COLUMNS IN A()
7100 REM AROW .... NUMBER OF ROWS IN A()
7110 REM B(j ..... INPUT MATRIX B()
7120 REM BCOL .•.. NUMBER OF COLUMNS IN B()
7130 REM BROW .... NUMBER OF ROWS IN B()
7140 REM RED$ .... "A" TO READ AI), "B" TO READ B
7150 REM LOCAL .... P,O
7160 REM ARRAY DIMENSIONS:
7170 REM A() ..... (AROW, ACOL)
7180 REM B() ..... (BROW, BCOL)
7190 REM
7200 IF RED$ = "B" THEN GOTO 7300
7210 IF REDS <> "A" THEN GOTO 7390
7220 REM
7230 REM READ MATRIX A
7240 FOR P = 1 TO AROW
7250 FOR 0 = 1 TO ACOL
7260 READ AIP,O)
7270 NEXT 0
7280 NEXT P
7290 GOTO 7370
7300 REM
7310 REM READ MATRIX B
7320 FOR P = 1 TO BROW
7330 FOR 0 = 1 TO BCOL
7340 READ B(P,O)
7350 NEXT 0
7360 NEXT P
7370 REM
7380 RETURN
7390 REM
7400 PRINT" INVALID REDS, RED$ "; REDS
7410 END
8000 REM WRITE OUTPUT MATRICES
8010 REM
8020 REM SUBROUTINE: MATWRT
8030 REM
8040 REM PRINTS MATRICES A, BAND c.
8050 REM
8060 REM VARIABLES:
8070 REM INPUT:
8080 REM A() ....• INPUT MATRIX A
8090 REM ACOL .... NUMBER OF COLUMNS IN A()
8100 REM AROW .... NUMBER OF ROWS IN A()
The Subroutines 109

8110 REM B() ..... INPUT MATRIX B


8120 REM BCOL .... NUMBER OF COLUMNS IN B()
8130 REM BROW .... NUMBER OF ROWS IN B( )
8140 REM C() ..... INPUT MATRIX C
8150 REM CCOL .... NUMBER OF COLUMNS IN C
816d REM CROW .... NUMBER OF ROWS IN C
8170 REM LOCAL: ... P, Q
8180 REM ARRAY DIMENSIONS:
8190 REM A() ..... (AROW, ACOL)
8200 REM B() ..... (BROW, BCOL)
8210 REM C() ..... (CROW, CCOL)
8220 REM
8230 PRINT
8240 IF WRT$ = "B" THEN GOTO 8360
8250 IF WRT$ = "c" THEN GOTO 8450
8260 IF WRT$ <> "A" THEN GO TO 8560
8270 REM
8280 REM PRINT MATRIX A
8290 FOR P = 1 TO AROW
8300 FOR Q = 1 TO ACOL
8310 PRINT A(P,Q); " " ,.
8320 NEXT Q
8330 PRINT
8340 NEXT P
8350 GOTO 8530
8360 REM
8370 REM PRINT MATRIX B
8380 FOR P = 1 TO BROW
8390 FOR Q = 1 TO BCOL
8400 PRINT B(P,Q); " " ,.
8410 NEXT Q
8420 PRINT
8430 NEXT P
8440 GOTO 8530
8450 REM
8460 REM PRINT MATRIX C
8470 FOR P = 1 TO CROW
8480 FOR Q = 1 TO CCOL
8490 PRINT C(P,Q); " " ,.
8500 NEXT Q
8510 PRINT
8520 NEXT P
8530 REM
8540 PRINT
8550 RETURN
8560 REM
8570 PRINT " INVALID WRT$, WRT$ "; WRT$
8580 END
110 Advanced BASIC Scientific Subroutines

Sample Programs

1. Evaluate (2.5A - B)T when

1000 REM SAMPLE PROGRAM: PMATTRN


1010 REM
1020 REM EVALUATE TRANSPOSE OF (2.5*A - B)
1030 REM REQUIRES SUBROUTINES MATRED, MATCNT, MATSBT,
1040 REM MATTRN, MATWRT
1050 REM
1060 REM ARRAY DIMENSIONS:
1070 DIM A(4,4)
1080 DIM B (4,4)
1090 DIM C( 4,4)
1100 REM
1110 DATA 3, 4, 3, 4, 2.5
1120 DATA 1, 2, 3, 4
1130 DATA 5, 6, 7, 8
1140 DATA 9, 10, 11, 12
1150 DATA 1, 4, 7, 10
1160 DATA 2, 5, 8, 11
1170 DATA 3, 6, 9, 12
1180 REM
1190 REM READ INPUT MATRICES AND PRINT
1200 REM CALL SUBROU'l'I NES MA'l'RED AND MA'l'WR'r
1210 READ AROW, ACOL, BROW, BCOL, CONST
1220 LET RED$ = "A"
1230 GOSUB 7000
1240 PRINT" INPUT MA'!'RIX A:"
1250 LET WRT$ = "A"
1260 GOSUB 8000
1270 LET RED$ = "B"
1280 GOSUB 7000
1290 PRINT" INPU'I' MATRIX B:"
1300 LET WRT$ = "B"
1310 GOSUB 8000
1320 REM
1330 REM EVALUATE 2.5*11.
1340 REM CALL SUBROUTINE MA'l'CN'r
1350 GOSUB 5000
1360 REM
1370 REM EVALUA'J'E A - B
The Subroutines 111

1380 REM CALL SUBROUT[NE MA'l'SBT


1390 GOSUB 3000
1400 REM
1410 REM EVALUA'I'E TRANSPOSE OF A
1420 REM CALL SUBROU'rINE MAT'l'RN
1430 GOSUB 4000
1440 REM
1450 REM PRINT RESUL'!,S
1460 REM CALL SUBROUTINE MATWR'l'
1470 PRINT " TRANSPOSE OF (2.5*A - B) "
1480 LE'r CROW 4
1490 LE'l' ccor~ = 3
1500 LET WRT$ = IIC"
1510 GOSUB 8000
1520 END

>RUN
INPUT MATRIX A:

1 2 3 4
5 6 7 8
9 10 11 12

INPUT MATRIX B:

1 4 7 10
2 5 8 11
3 6 9 12

TRANSPOSE OF (2.5*A - B)

1.5 10.5 19.5


1 10 19
0.5 9.5 18.5
0 9 18

In the above example the result is obtained first by multiplying matrix A by


2.5 then subtracting matrix B and finally transposing the resultant matrix. This
example illustrates some of the laws of matrix algebra.
2. EvaluateA.B andB.A when

A= ( ; : D
n=C: _; ~)
112 Advanced BASIC Scientific Subroutines

1000 REM SAMPLE PROGRAM: PMATMUL


1010 REM
1020 REM EVALUATE A*B AND B*A
1030 REM REQUIRES SUBROUTINES MATRED, MATMUL, MATWRT
1040 REM
1050 REM ARRAY DIMENSIONS:
1060 DIM A(3,3)
1070 DIM B(3,3)
1080 DIM C(3,3)
1090 REM
1100 DATA 3, 3, 3, 3
1110 DATA 2, 1, 2, 3, 5, 7, 1, 0, 1
1120 DATA -3, 1, 0, 6, 2, 1, 1, ~1, 2
1130 REM
1140 REM READ INPUT MATRICES AND PRINT
1150 REM CALL SUBROUTINES MATRED AND MATWRT
1160 READ AROW, ACOL, BROW, BCOL
1170 LET RED$ • "A"
1180 GOSUB 7000
1190 PRINT" INPUT MATRIX A:"
1200 LET WRT$ • "A"
1210 GOSUB 8000
1220 LET RED$ • "B"
1230 GOSUB 7000
1240 PRINT" INPUT MATRIX B:"
1250 LET WRT$ • "B"
1260 GOSUB 8000
1270 REM
1280 REM EVALUATE A*B AND PRINT RESULTS
1290 REM CALL SUBROUTINES MATMUL AND MATWRT
1300 PRINT" OUTPUT MATRIX C = A*B = "
1310 GOSUB 6000
1320 LET WRT$ • "C"
1330 LET CCOL • BCOL
1340 LET CROW • AROW
1350 GOSUB 8000
1360 REM
1370 REM SET A • PREVIOUS B AND B PREVIOUS A
1380 RESTORE 1110
1390 LET RED$ • "B"
1400 GOSUB 7000
1410 LET RED$ • "A"
1420 GOSUB 7000
1430 REM
1440 REM EVALUATE B*A AND PRINT RESULTS
1450 REM CALL SUBROUTINES MATMUL AND MATWRT
1460 PRINT" OUTPUT MATRIX C • B*A ."
1470 GOSUB 6000
1480 GOSUB 8000
1490 END
The Subroutines 113

>RUN
INPUT MATRIX A:

2 1 2
3 5 7
1 0 1

INPUT MATRIX B:

-3 1 0
6 2 1
1 -1 2

OUTPUT MATRIX C A*B

2 2 5
28 6 19
-2 0 2

OUTPUT MATRIX C B*A

-3 2 1
19 16 27
1 -4 -3

The products of A.B and B.A are not equal. This example illustrates the non-
commutative law of matrix multiplication.

Notes

1. A check for compatibility of two matrices is made before addition, subtraction


and multiplication of two matrices. If the matrices are incompatible then the main
program is terminated.
2. Stephenson (1969), Stroud (1982), Kreyszig (1983) and Mason (1984) are
suggested for further reading.
114 Advanced BASIC Scientific Subroutines

EIGENVECTORS AND EIGENVALUES

Subroutine: MATEGN

Description

Finds the eigenvectors and eigenvalues of a real symmetric matrix by the Jacobi
diagonalisation method.

Method

If we can find a number p and a vector v for a matrix A such that


A. v =p.v
the number p and the vector v are called eigenvalue and eigenvector of the matrix
A respectively. The above equation can also be written as
(A - p.I).v =0
This equation represents a linear homogeneous system of equations whose non-
trivial solutions exist only if det(A - p.I) = O. This consists of an algebraic equation
of degree n in p where n is the order of matrix A . Determination of eigenvalues and
eigenvectors of a matrix is then reduced to finding the roots of an algebraic equation
and to solving n linear homogeneous systems of equations. In reality, except for a
few special cases, a direct method for computation of eigenvalues from the
equation det(A - p.I) = 0 is never used.
Depending on the nature of matrix A, various methods have been devised to
solve eigenvalues and eigenvectors. If matrix A is a real symmetric, then its eigen-
values and eigenvectors are real. (Note that if A is symmetric, then transpose of
A equals A.) The technique used here involves diagonalisation of the original matrix
by use of an orthogonal matrix transformation. This method was originally devised
by C. Jacobi and recently modified by J. von Neumann (Ralston and Wilf, 1962).
It is an iterative method which is allowed to proceed several times until the required
accuracy is obtained.

Subroutine Listing

2000 REM EIGENVECTORS AND EIGENVALUES


2010 REM
2020 REM SUBROUTINE: MATEGN
2030 REM
2040 REM FINDS EIGENVALUES AND VECTORS OF REAL
2050 REM SYMMETRIC MATRIX BY JACOBI DIAGONALISATION
2060 REM METHOD
2070 REM
2080 REM VARIABLES:
The Subroutines lI5

2090 REM INPUT:


2100 REM A() ..... REAL SYMMETRIC MATRIX
2110 REM ODR •••.• ORDER OF MATRIX
2120 REM OUTPUT:
2130 REM A() ••••• MATRIX CONTAINING EIGENVALUES
2140 REM ALONG THE PRINCIPAL DIAGONAL
2150 REM C() ••..• MATRIX OF EIGENVECTORS
2160 REM LOCAL: .•• CST, CST2, FINORH, NORM, P, Q, R,
2170 REM SNT, SNT2, TLRNC, U, V1, V2, V3,
2180 REM V4, V5, V6, V7, V8, V9
2190 REM ARRAY DIMENSIONS:
2200 REM A() ••.•. (ODR,ODR)
2210 REM C() ••..• (ODR,ODR)
2220 REM
2230 LET TLRNC = 1E-6
2240 LET U = 0
2250 REM
2260 REM SET MATRIX C TO ZERO
2270 FOR P= 1 TO ODR
2280 FOR Q = 1 TO ODR
2290 LET C(P,Q) = 0
2300 NEXT Q
2310 NEXT P
2320 REM
2330 REM INPUT CHECK
2340 FOR P = 1 TO ODR
2350 FOR Q = 1 TO ODR
2360 IF A(P,Q) <> A(Q,P) THEN GO TO 2710
2370 NEXT Q
2380 NEXT P
2390 REM
2400 REM COMPUTE INITIAL NORM
2410 LET NORM = 0
2420 FOR P = J. TO ODR
2430 FOR Q = 1 TO ODR
2440 IF Q P THEN GOTO 2460
2450 LET NORM = NORM + A(P,Q)*A(P,Q)
2460 REM
2470 NEXT Q
2480 NEXT P
2490 IF NORM < TLRNC*TLRNC THEN GOTO 2690
2500 1~Il:M
2510 REM GENERATE UNIT MATRIX
2520 FOR P = 1 TO ODR
2530 LET C(P,P) = 1
2540 NEXT P
2550 REM
2560 REM COMPUTE FINAL NORM
2570 LET NORM = SQR(NORM)
2580 LET FINORM = NORM*TLRNC
2590 REM
2600 REM REVISED THRESHOLD
2610 LET NORM = NORM/ODR
2620 REM
2630 GOSUB 2740
116 Advanced BASIC Scientific Subroutines

2640 IF U - 1 <> 0 THEN GO TO 2670


2650 LET U = 0
2660 GOTO 2620
2670 REM
2680 IF NORM - FINORM > 0 THEN GOTO 2600
2690 REM
2700 RETURN
2710 REM
2720 PRINT" MATRIX NOT SYMMETRIC"
2730 END
2740 REM DIAGONALISATION
2750 FOR P = 2 TO ODR
2760 FOR Q = 1 TO P - 1
2770 IF ABS (A(Q,P» - NORM < 0 THEN GOTO 3130
2780 LET U = 1
2790 LET V1 -A(Q,P)
2800 LET V2 = (A(Q,Q) - A(P,P»*0.5
2810 LET V4 = SQR(V1*V1 + V2*V2)
2820 LET V3 = Vl/V4
2830 IF V2 < 0 THEN LET V3 = -V3
2840 LET V4 = SQR(2*(1 + SQR(l - V3*V3»)
2850 LET SNT = V3/V4
2860 LET SNT2 = SNT*SNT
2870 LET CST = SQR(l - SNT2)
2880 FOR R = 1 TO ODR
2890 IF R = P OR R = Q THEN GOTO 2930
2900 LET V4 = A(R,Q)*CST - A(R,P)*SNT
2910 LET A(R,P) = A(R,Q)*SNT + A(R,P)*CST
2920 LET A(R,Q) = V4
2930 REM
2940 LET V5 = C(R,Q)*CST - C(R,P)*SNT
2950 LET C(R,P) = C(R,Q)*SNT + C(R,P)*CST
2960 LET C(R,Q) = V5
2970 NEXT R
2980 LET CST2 = CST*CST
2990 LET V6 = SNT*CST
3000 LET V9 2*V6*A(Q,P)
3010 LET V7 = A(Q,Q)*CST2 + A(P,P)*SNT2 - V9
3020 LET V8 A(Q,Q)*SNT2 + A(P,P)*CST2 + V9
3030 LET V4 CST2 - SNT2
3040 LET V9 = V4*A(Q,P)
3050 LET A(Q,P) = (A(Q,Q) - A(P,P»*V6 + V9
3060 LET A(P,Q) = A(Q,P)
3070 LET A(Q,Q) = V7
3080 LET A(P,P) = V8
3090 FOR R = 1 TO ODR
3100 LET A(Q,R) A(R,Q)
3110 LET A(P,R) = A(R,P)
3120 NEXT R
3130 REM
3140 NEXT Q
3150 NEXT P
3160 RETURN
The Subroutines 117

Sample Program

Find eigenvalues and eigenvectors of a (4 x 4) matrix A where


8 5 4.5
8 6 5.3 4
A=
5 5.3 9 7
4.5 4 7 8

1000 REH SAMPLE PROGRAH: PHATEGN


1010 REH
1020 REH TO EVALUATE EIGENVALUES AND EIGENVECTORS
1030 REH REQUIRES SUBROUTINES HATRED, HATEGN, HATWRT
1040 REH
1050 REH ARRAY DIHENSIONS:
1060 DIH A(4,4)
1070 DIH C(4,4)
1080 REH
1090 DATA 4, 4, 4, "A", 4, 4, "A"
1100 DATA 11, 8, 5, 4.5
1110 DATA 8, 6, 5.3, 4
1120 DATA 5, 5.3, 9, 7
1130 DATA 4.5, 4, 7, 8
1140 REH
1150 REH READ AND PRINT INPUT HATRIX
1160 REH CALL SUBROUTINES HATRED, HATWRT
1170 READ ODR, AROW, ACOL, WRT$, CROW, CCOL, RED$
1180 GOSUB 7000
1190 PRINT" INPUT HATRIX A:"
1200 GOSUB 8000
1210 REH
1220 REH EVALUATE EIGENVALUES AND VECTORS AND PRINT
1230 REH RESULTS. CALL SUBROUTINES HATEGN, HATWRT
1240 GOSUB 2000
1250 PRINT" EIGENVALUES"
1260 PRINT
1270 FOR I = 1 TO ODR
1280 PRINT A(I,I)
1290 NEXT I
1300 PRINT
1310 PRINT" EIGENVECTORS"
1320 LET WRT$ = "c"
1330 GOSUB 8000
1340 END
118 Advanced BASIC Scientific Subroutines

Escape
>RUN
INPUT MATRIX A:

11 8 5 4.5
8 6 5.3 4
5 5.3 9 7
4.5 4 7 8

EIGENVALUES

25.594332
=0.21026969
6.9957887
1. 6201487

EIGENVECTORS

0.56739933 -0 .. 49713577 -0.62709051 0.19409151


0.46192228 0.80695729 -0.29136584 -0.22484146
0.50952013 -0.29194269 0.49400958 -0.64118112
0.45285211 0.12823972 0.5270844 0.70757~43

The column of eigenvalues printed above are the principal diagonal elements
of the output array A( ). The remaining elements are either zero or very small.
The first column of eigenvector matrix (output array B( )) corresponds to the
first eigenvalues and so forth. Thus
25.594332 corresponds to 0.56739933
0.46192228
0.50952013
0.45285211
etc.

Notes

1. In subroutine MATEGN the accuracy tolerance variable TLRNC is set for


1.0E - 6. This value is adequate for computers working with eight significant
figures, however a smaller value may be given for computers working with higher
significant figures or double precision numbers.
2. Conte (1965) and Froberg (1970) are suggested for further reading.
The Subroutines 119

MATRIX INVERSION AND DETERMINANT OF A MATRIX

Subroutines: MAT/NV and MATDET

Description

Computes an inverse and a determinant of a matrix by Gauss-elimination method


with pivoting.

Method

A system of simultaneous equations can be represented by a matrix equation


A .X = B where A is the matrix of the coefficients of the unknowns contained in
the matrix X and matrix B contains the constants. This system of equations may
be solved by a method known as 'Gauss-elimination with pivotal condensation' .
This is a direct method and extracts the solution in a fmite number of arithmetic
operations. In the absence of round-off and other errors this method should
provide an exact solution. A technique called pivoting is often used to minimise the
growth of round-off errors.
The main operations of this method are:
(a) adjoin matrix A withB, that is, A I B;
(b) pick up the pivotal element with row interchanges if necessary;
(c) reduce the matrixA to an upper-triangular form by elimination; and
(d) fmally solve for unknowns in the reverse order by back-substitution.
If now C is the inverse of a matrix A then
A.C=J
where J is the identity matrix. This equation resembles A. X = B and can be solved
by the above method thus extracting C.
In the above method when the matrix A is reduced to a triangular form, then
the determinant of A is obtained by the product of the diagonal elements; this
being a property of a triangular matrix.
Operations (b) and (c) are carried out in subroutine MATDET which also
evaluates the determinant of the given matrix.
Subroutine MATINV finds the inverse of a matrix A by
(i) generating matrix J of the same order as matrixA;
(ii) adjoining A with J to give A I J;
(iii) using subroutine MATDET; and
(iv) performing operation (d).

The subroutines MATDET and MATINY use an array A() to store the input
matrix A and A I J respectively. Therefore the array A( ) will have different number
of columns depending on the subroutine used. For example, if A is an n x n
120 Advanced BASIC Scientific Subroutines

matrix, then the maximum number of columns (variable MeOL) for array A()
will be n for subroutine MATDET and 2n for MATINY.
The array A() is also used for storing the results of the computation in sub·
routine MATINY, consequently the required inverse of matrix A is stored in the
first n x n rows and columns of the array A().

Subroutine Listings

2000 REM MATRIX INVERSION


2010 REM
2020 REM SUBROUTINE: MATINV
2030 REM
2040 REM FINDS INVERSE OF A MATRIX BY GAUSS
2050 REM ELIMINATION WITH PIVOTAL CONDENSATION
2060 REM REQUIRES SUBROUTINE MATDET
2070 REM
2080 REM VARIABLES:
2090 REM INPUT:
2100 REM A() •.••. INPUT MATRIX
2110 REM MCOL .... MAX. NO. OF COLS. IN A() (=2*ODR)
2120 REM ODR •.... ORDER OF MATRIX
2130 REM OUTPUT:
2140 REM A() ..... THE ORIGINAL MATRIX IS OVER-
2150 REM WRITTEN BY THE INVERSE MATRIX
2160 REM LOCAL: ••. MDET, P, Q, R, W()
2170 REM ARRAY DIMENSIONS:
2180 REM A() .•... (ODR,2*ODR)
2190 REM W() ..•.. (ODR + 1)
2200 REM
2210 REM AUGMENT MATRIX A()
2220 FOR P= 1 TO ODR
2230 FOR Q = ODR + 1 TO MCOL
2240 LET A(P,Q) = 0
2250 NEXT Q
2260 LET A(P,P + ODR) = 1
2270 NEXT P
2280 REM
2290 REM EVALUATE DETERMINANT
2300 REM CALL SUBROUTINE MATDET
2310 GOSUB 3000
2320 IF MDET = 0 THEN GOTO 2550
2330 REM
2340 REM BACK SUBSTITUTION
2350 FOR P = ODR + 1 TO MCOL
2360 FOR Q = ODR TO 1 STEP -1
2370 LET W(Q) = A(Q,P)
2380 IF Q = P THEN GOTO 2420
2390 FOR R = Q + 1 TO ODR
2400 LET W(Q) = W(Q) - W(R)*A(Q,R)
2410 NEXT R
2420 REM
2430 LET W(Q) = W(Q)/A(Q,Q)
The Subroutines 121

2440 NEXT Q
2450 FOR Q = 1 TO ODR
2460 LET A(Q,P) = W(Q)
2470 NEXT Q
2480 NEXT P
2490 FOR P = 1 TO ODR
2500 FOR Q = 1 TO ODR
2510 LET A(P,Q) = A(P,ODR + Q)
2520 NEXT Q
2530 NEXT P
2540 RETURN
2550 REM
2560 PRINT " MATRIX A IS SINGULAR AND HAS NO INVERSE"
2570 END
3000 REM DETERMINANT OF A MATRIX
3010 REM
3020 REM SUBROUTINE: MATDET
3030 REM
3040 REM EVALUATION OF THE DETERMINANT OF A MATRIX
3050 REM BY GAUSS ELIMINATION WITH PIVOTING
3060 REM
3070 REM VARIABLES:
3080 REM INPUT:
3090 REM A() ..... INPUT MATRIX
3100 REM MCOL .... MAXIMUM NUMBER OF COLUMNS IN A()
3110 REM ODR ..... ORDER OF MATRIX
3120 REM OUTPUT:
3130 REM MDET ..... DETERMINANT
3140 REM LOCAL: ...• LMNT, MLTPLR, NDET, PVOT, ROWM,
3150 REM SIGMA, SIGN, rLRNC
3160 REM ARRAY DIMENSIONS:
3170 REM A() ...... (ODR,ODR)
3180 REM
3190 LET SIGN = 1
3200 LET TLRNC = 1E-3
3210 REM
3220 REM EVALUATE SUM OF SQUARES OF ELEMENTS
3230 GOSUB 3740
3240 REM
3250 REM PICK UP PIVOT ELEMENT
3260 FOR P = 1 TO ODR - 1
3270 LET ROWM = P
3280 LET PVOT = ABS(A(P,P»
3290 FOR Q = P + 1 TO ODR
3300 LET LMNT = ABS(A(Q,P»
3310 IF LMNT <= PVOT THEN GOTO 3340
3320 LET ROWM Q
3330 LET PVOT = LMNT
3340 REM
3350 NEXT Q
3360 REM
3370 REM ROW INTERCHANGE
3380 IF ROWM = P THEN GO TO 3460
3390 FOR R = P TO MeOL
122 Advanced BASIC Scientific Subroutines

3400 LET LMNT = A(P,R}


3410 LET A(P,R} = A(ROWM,R}
3420 LET A(ROWM,R} = LMNT
3430 NEXT R
3440 LET SIGN = -SIGN
3450 REM
3460 REM TRIANGULARISATION
3470 FOR Q = P + 1 TO ODR
3480 IF A(Q,P} = 0 THEN GOTO 3530
3490 LET MLTPLR = -A(Q,P}/A(P,P}
3500 FOR R = P TO MCOL
3510 LET A(Q,R} = A(Q,R} + MLTPLR*A(P,R}
3520 NEXT R
3530 REM
3540 NEXT Q
3550 NEXT P
3560 REM
3570 REM DETERMINANT
3580 LET MDET = 1
3590 LET LMNT = 1
3600 FOR P = 1 TO ODR
3610 LET LMNT = LMNT*A(P,P}
3620 NEXT P
3630 LET MDET = SIGN*LMNT
3640 IF MDET = 0 THEN GOTO 3710
3650 REM
3660 REM TEST FOR ILL-CONDITIONING
3670 LET NDET = MDET/SQR(SIGMA}
3680 IF ABS(NDET} > TLRNC THEN GOTO 3710
3690 PRINT" MATRIX A MAY BE ILL-CONDITIONED,"
3700 PRINT " ACCURACY DOUBTFUL"
3710 REM
3720 RETURN
3730 REM
3740 REM SUM OF SQUARES
3750 LET SIGMA = 0
3760 FOR P = 1 TO ODR
3770 FOR Q = 1 TO ODR
3780 LET SIGMA = SIGMA + A(P,Q}*A(P,Q}
3790 NEXT Q
3800 NEXT P
3810 RETURN

Sample Program

Find an inverse and a determinant of matrix A where


0.88 1.33 0.25
1.50 5.45 0.64
A= 2.50 4.84 0.93
3.40 6.78 0.11
7.80 0.99 1.88
The Subroutines 123

1000 REM SAMPLE PROGRAM: PMATINV


1010 REM
1020 REM EVALUATES THE DETERMINANT AND INVERSE OF
1030 REM A MATRIX. REQUIRES SUBROUTINES MATRED,
1040 REM MATWRT, MATINV, MATDET
1050 REM
1060 REM ARRAY DIMENSIONS:
1070 DIM A(5,10)
1080 DIM W( 6)
1090 REM
1100 DATA 5, 5, "A", 10, 5, "A"
1110 DATA 0.15, 0.88, 1.33, 0.25, 0.5
1120 DATA 0.34, 1.5, 5.45, 0.64, 1.7
1130 DATA 0.55, 2.5, 4.84, 0.93, 1.87
1140 DATA 0.67, 3.4, 6.78, 0.11, 3.54
1150 DATA 0.7, 7.8, 0.99, 1.88, 1
1160 REM
1170 REM READ AND PRINT INPUT MATRIX
1180 REM CALL SUBROUTINES MATRED, MATWRT
1190 READ ACOL, AROW, RED$, MCOL, ODR, WRT$
1200 GOSUB 7000
1210 PRINT" INPUT MATRIX A:"
1220 GOSUB 8000
1230 REM
1240 REM EVALUATE AND PRINT RESULTS
1250 REM CALL SUBROUTINES MATINV, MATWRT
1260 GOSUB 2000
1270 PRINT" DETERMINANT = "; MDET
1280 PRINT
1290 PRINT " INVERSE MATRIX"
1300 GOSUB 8000
1310 END

>RUN
INPUT MATRIX A:
0.15 0.88 1. 33 0.25 0.5
0.34 1.5 5.45 0.64 1.7
0.55 2.5 4.84 0.93 1.87
0.67 3.4 6.78 0.11 3.54
0.7 7;8 0.99 1. 88 1
DETERMINANT -0.28126
INVERSE MATRIX

55.075 -10.293 -0.80361 -1.4689 -3.3362


3.0852 0.13952 -1.0963 5.3338E-2 8.1419E-2
6.0447 -6.4357E-2 -1.0621 -0.19254 -0.24525
-23.601 2.295 3.7457 -4.0679E-2 1. 0385
-24.231 1. 8661 3.1228 0.87931 0.99068
124 Advanced BASIC Scientific Subroutines

No ill-conditioning is detected therefore, the results are accurate to the precision


determined by the machine (usually eight or nine significant figures for home
computers).

Notes

1. Ill-conditioned matrix is detected by the use of the following formula:

detA
-----~1
n n
V(L LAn
;=1 ;=1 '

If this condition is satisfied then a warning is issued without the interruption of the
main program. This test is carried out in subroutine MATDET. Note that the
critical ratio, NDET, triggers the warning when it is';;;; TLRNC. This value may
be adjusted to suit a particular application. Caution should be exercised when ill-
conditioning is detected as the accuracy of the results may be affected.
2. Conte (1965), Bajpai et al. (1974) and Mason (1984) are suggested for further
reading.
The Subroutines 125

2. 7 Interpolation

INTERPOLATION BY THE LAGRANGE POLYNOMIAL METHOD

Subroutine: INTPLN

Description

Evaluates a function at a given point by first approximating the function from a


given table of function values by use of the Lagrange interpolating polynomial
method.

Method

Given Yj =Y(Xj) at a set of distinct ordinates Xj (i = 1, 2, ... ,n), it is required


to evaluate this function at a given point x between data ordinates which are
arbitrarily spaced. If P(x) is the approximating polynomial, then by the Lagrange
interpolation formula
n
y(x) ~ p(x) = ~ y(xj).Llx)
i=1

where
n
Lt(x) = IT (x - Xj)/(Xt - Xj)
;=1
j,pj

and if the Li (x) have the property that


Lj(x) = 0 for i =1= k
= 1 for i = k where k = 1,2, ... ,n
then
n
P(Xk) = ~ y(xj)L j (xic) ~ Y(Xk)
j=1

Subroutine Listing
2000 REM INTERPOLATION
2010 REM
2020 REM SUBROUTINE: INTPLN
2030 REM
2040 REM EVALUATES A FUNCTION AT A GIVEN POINT BY
2050 REM APPROXIMATING THE FUNCTION FROM A TABLE
2060 REM OF FUNCTION VALUES. USES LAGRANGE'S FORMULA
2070 REM
2080 REM VARIABLES:
2090 REM INPUT:
2100 REM A() •...• ARRAY OF X COORDINATE VALUES
2110 REM B() ••••• ARRAY OF Y COORDINATE VALUES
126 Advanced BASIC Scientific Subroutines

2120 REM NUMDAT .. NUMBER OF DATA POINTS


2130 REM X....... POINT OF INTERPOLATION
2140 REM OUTPUT:
2150 REM Y...•... VALUE AT POINT OF INTERPOLATION
2160 REM LOCAL: ..• P, Q, V1
2170 REM ARRAY DIMENSIONS:
2180 REM A() ..... (NUMDAT)
2190 REM B() ..... (NUMDAT)
2200 REM
2210 LET Y = 0
2220 FOR P = 1 TO NUMDAT
2230 LET V1 = 1
2240 FOR Q = 1 TO NUMDAT
~250 IF Q = P THEN GOTO 2270
2260 LET V1 = V1*(X - A(Q»/(A(P) - A(Q»
2270 REM
2280 NEXT Q
2290 LET Y = Y + B(P)*V1
2300 NEXT P
2310 RETURN

Sample Program

From the following table of function values y = [(x), find the value of y at x =
1.65 by use of the Lagrange interpolating polynomial.
x 0.16 0.25 0.66 1.00 1.44 1.88 2.00 2.30 2.74 3.14
[(x) -0.68 -0.51 0.23 0.68 0.98 0.91 0.82 0.49 -0.22 -1.00

1000 REM SAMPLE PROGRAM: PINTPLN


1010 REM
1020 REM ARRAY DIMENSIONS:
1030 DIM A(10)
1040 DIM B(10)
1050 REM
1060 DATA 10, 1. 65
1070 DATA 0.16, -0.68, 0.25, -0.51, 0.66, 0.23
1080 DATA 1, 0.68, 1.44, 0.98, 1.88, 0.91, 2, 0.82
1090 DATA 2.3, 0.49, 2.74, -0.22, 3.14, -1
1100 REM
1110 REM READ INPUT DATA
1120 READ NUMDAT, X
1130 FOR I = 1 TO NUMDAT
1140 READ A( I ), B (I)
1150 NEXT I
1160 REM
1170 REM EVALUATE POINT Y(X) AND PRINT RESULT
1180 REM CALL SUBROUTINE INTPLN
1190 GOSUB 2000
The Subroutines 127

1200 PRINT" YIn; X; ") = "; Y


1210 END

>RUN
Y(1.65) 0.99837168

This example illustrates one of the main applications of the Lagrangian inter-
polating polynomial; that is, evaluating a function at some unknown point when
values of the functions are known at a set of tabular points.

Notes

1. This method fails to give meaningful results if, over the range of the input data,
the function to be interpolated has more than one value of y for any value of x. A
sketch of the data points can be helpful in indicating the nature of the function.
2. It is difficult to estimate errors in interpolation without a prior knowledge of the
nature of the function to be interpolated.
3. Conte (1965), Fox and Mayers (1968) and Conte and De Boor (1972) are sug-
gested for further reading.
128 Advanced BASIC Scientific Subroutines

2.8 Numerical Analysis

GENERA nON OF CHEBYSHEV POLYNOMIAL

Subroutine: CHBSHV

Description

(a) Generates a Chebyshev Polynomial Tn(x) of the form


A1xn + A 2 x n - 1 + ... + Anx + A n + 1; and
(b) expresses powers of x in terms of series of Chebyshev Polynomial, thus
xn =2-(n-1) [BITn +B2 T n - 1 + ... +Bn+1 Tol

Method

The Chebyshev Polynomial of degree n is defined by


Tn(x) = cos(n.arc cos x) -1 EO;; x EO;; 1
Putting x = cos t:
Tn(x) = cos nt -'IT EO;; t EO;; 'IT

For n = 0, To (x) = cos 0 = 1 and


n= 1, T1(x) = cos t=x.
Higher-degree polynomials are obtained by making use of the recurrence relation-
ship:
Tn +1 (x) = 2xTn(x) - T n - 1(x) n = 1,2,3, ...
thus n = 2, T2 (x) = 2X2 - 1
n = 3, T3(X) = 4x 3 - 3x and so on.
Chebyshev Polynomials are used as an economical means of approximating a
function by polynomials. In this situation powers of x are expressed in terms of
the Chebyshev Polynomials as linear combinations of them. For example
1 =To
X=TI
x 2 =r l (T2 + To)
x 3 = 2 -2 (T3 + 3T1 ) and so on.
The general coefficient in the expansion
Xk = Wn Tn is Bn where
The Subroutines 129

Bn = 2 1- k (n +kk)/2)

If k is odd, n = 1,3,5, ... ,k


If k is even, n =0, 2, 4, ... ,k
°
If k is 0, Bn = except when n =0, since Bo = 1.
The coefficients of Tn(x) are stored in the array A() with descending powers
of x, and likewise the coefficients of xn are stored in the array B( ) with descending
order of Tn (x). Since Chebyshev Polynomials are subscripted Tn(x) where n = 0,
1,2, ... etc., the dimensions of the arrays A() and B() should be one more than
the degree of polynomial required.

Subroutine Listing

2000 REM CHEBYSHEV POLYNOMIAL


2010 REM
2020 REM SUBROUTINE: CHBSHV
2030 REM
2040 REM GENERATES CHEBYSHEV POLYNOMIALS OF THE FORM
2050 REM A(l)*X AN + A(2)*X A(N-1)+ •.. +A(N)*X + A(N+1)
2060 REM AND EXPRESSES POWERS OF X IN TERMS OF SERIES
2070 REM OF CHEBYSHEV POLYNOMIAL THUS XAN = 2 (1-N)* A

2080 REM [B(l)*T(N) + B(2)*T(N-1) + ••. + B(N+1)]


2090 REM
2100 REM VARIABLES:
2110 REM INPUT:
2120 REM NUMDEG .. DEGREE OF POLYNOMIAL
2130 REM OUTPUT:
2140 REM A() .•... ARRAY OF COEFFICIENTS OF CHEBYSHEV
2150 REM POLYNOMIAL
2160 REM B() .•... ARRAY OF COEFFICIENTS IN THE
2170 REM EXPANSION OF XAN IN TERMS OF
2180 REM CHEBYSHEV POLYNOMIALS
2190 REM LOCAL: ... c ( ), D ( ), P, Q, R, SIGMA,
2200 REM V1, V2, V3
2210 REM ARRAY DIMENSIONS:
2220 REM A() ..••• (NUMDEG + 1)
2230 REM B() ...•. (NUMDEG + 1)
2240 REM C() ..... (NUMDEG + 1)
2250 REM D ( ) ..... (NUMDEG + 1)
2260 REM
2270 IF NUMDEG > 1 THEN GOTO 2310
2280 LET A(l) = 1
2290 LET B(l) = 1
2300 GOTO 2730
2310 REM
2320 REM DETERMINE XAN IN TERMS OF T(N)
2330 LET Q = NUMDEG
2340 FOR P = 1 TO NUMDEG
2350 LET V3 = 2*P - 1
2360 IF V3 > NUMDEG + 1 THEN GOTO 2490
2370 LET B(V3) = 1
130 Advanced BASIC Scientific Subroutines

2380 LET V1 = NUMDEG


2390 LET V2 = 1
2400 LET SIGMA = 1
2410 FOR R = 1 TO Q
2420 LET SIGMA = SIGMA *V1/V2
2430 LET V1 = V1 - 1
2440 LET V2 = V2 + 1
2450 NEXT R
2460 LET B(V3) = B(V3)* SIGMA
2470 LET B(V3 + 1) = 0
2480 LET Q = Q - 1
2490 REM
2500 NEXT P
2510 LET B(NUMDEG + 1) = 0.5*B(NUMDEG + 1)
2520 REM
2530 REM DETERMINE T(N) IN TERMS OF X(N)
2540 FOR P = 1 TO NUMDEG + 1
2550 LET A(P) 0
2560 LET C(P) = 0
2570 LET D(P) = 0
2580 NEXT P
2590 LET C(l) = 1
2600 LET D(l) = 1
2610 FOR P = 2 TO NUMDEG
2620 LET Q = P + 1
2630 LET A(l) = 2*C(1)
2640 LET A(2) = 2*C(2)
2650 FOR R = 3 TO Q
2660 LET A(R) = 2*C(R) - D(R - 2)
2670 NEXT R
2680 FOR R = 1 TO Q
2690 LET D(R) = C(R)
2700 LET C(R) = A(R)
2710 NEXT R
2720 NEXT P
2730 RETURN

Somple Program

Generate Chebyshev Polynomials up to degree 9 and express x, x 2 , ••• ,x9 in


terms of Chebyshev Polynomial series. Tabulate results.

1000 REM SAMPLE PROGRAM: PCHBSHV


1010 REM
1020 REM GENERATES TABLES OF CHEBYSHEV POLYNOMIALS
1030 REM
1040 REM VARIABLES:
1050 REM N1 ....... MAXIMUM DEGREE OF POLYNOMIAL
1060 REM ARRAY DIMENSIONS:
1070 DIM A(10)
1080 DIM B(10)
1090 DIM C(10)
The Subroutines 131

1100 DIM D(10}


1110 REM
1120 REM SET INITIAL VALUE
1130 LET N1 = 9
1140 REM
1150 REM COMPUTE CHEBYSHEV POLYNOMIALS
1160 REM CALL SUBROUTINE CHBSHV
1170 FOR I = 1 TO N1
1180 LET NUMDEG = I
1190 GOSUB 2000
1200 PRINT" COEFFICIENTS OF T("; I; H):"
1210 FOR J = 1 TO I + 1
1220 PRINT A(J};
1230 NEXT J
1240 PRINT
1250 PRINT" COEFFICIENTS OF X-Hi I
1260 FOR J = 1 TO I + 1
1270 PRINT B(J};
1280 NEXT J
1290 PRINT
1300 NEXT I
1310 END

>RUN
COEFFICIENTS OF T( 1} :
1 0
COEFFICIENTS OF X-1
1 0
COEFFICIENTS OF T( 2} :
2 0 -1
COEFFICIENTS OF X-2
1 0 1
COEFFICIENTS OF T( 3) :
4 0 -3 0
COEFFICIENTS OF X-3
1 0 3 0
COEFFICIENTS OF T( 4) :
8 0 -8 0 1
COEFFICIENTS OF X-4
1 0 4 0 3
COEFFICIENTS OF T( 5) :
16 0 -20 0 5 0
COEFFICIENTS OF X-5
1 0 5 0 10 0
COEFFICIENTS OF T( 6} :
32 0 -48 0 18 0 -1
COEFFICIENTS OF X-6
1 0 6 0 15 0 10
COEFFICIENTS OF T( 7) :
64 o -112 0 56 0 -7 0
COEFFICIENTS OF X-7
1 0 7 0 21 0 35 0
COEFFICIENTS OF T( 8) :
128 o -256 0 160 0 -32 0 1
132 Advanced BASIC Scientific Subroutines

COEFFICIENTS OF r8
1 0 8 0 28 0 56 0 35
COEFFICIENTS OF T( 9) :
256 o -576 0 432 0 -120 0 9 0
COEFFICIENTS OF r9
1 0 9 0 36 0 84 0 126 0

The required tables are:


To (x) =
T. (YI
.... 1 , .... ,/ x
Tz(x) 2x 2 -1
T3(X) = 4x 3 - 3x
T4(X) = 8x 4 - 8X2 + 1
Ts(x) 16x 5 - 20x3 + 5x

T6(X) 32x 6 - 48x4 + 18x 2 - 1


T7(X) 64x 7 - 112x 5 + 56x 3 -7x
Ts(x) = 128x 8 - 256x 6 + 160x4 - 32x 2 + 1
T 9 (x) 256x 9 - 576x 7 + 432x 5 - 120x3 + 9x
To
x = Tt
x2 rt(Tz + To)
x3 r2(T3 + Td
X4 r 3 (T4 + 4Tz + 3To)
XS = r4(Ts + 5T3 + lOTt)
x6 rS(T6 + 6T4 + 15T2 + 10To)
x7 = r 6(T7 + 7Ts + 21T3 + 35Tt )
x8 r 7 (Ts + 8T6 + 28T4 + 56T2 + 35To)
x9 r8(T9 + 9T7 + 36Ts + 84T3 + 126Tt )
These tables of expressions are regarded as identities and are used in the
method of economisation of polynomials.

Note

Hamming (1962) Ralston and Wilf (1'962), Conte and De Boor (1972) and Bajpai
et al. (1974) are suggested for further reading.
The Subroutines 133

FOURIER ANALYSIS

Subroutine: FURIER

Description

Approximates the periodic function y(x) specified by a table of observed values


with a fmite Fourier series of the form:
f(x) =aO + ~ (a,cos(r. k) + b,sin(r,k»
00

,=1
where n is the number of equally-spaced data points; (n - 1) is the period of the
function; r is the set of harmonic indices; and k = 2rrx/(n - 1).

Method

To fit the data points Y(Xl)' y(xz) ... ,y(xn) to the Fourier series, the harmonic
coefficients a, and b, need to be computed. The method used in the computation
is indicated in the following formulae.

n-l
ao =(l/(n - 1»(y(xl) + ~ Y(Xj» and b o =0
;=2
To improve the general level of accuracy, the average value, ao, is subtracted
from the data in the following calculations:
n-l
a, =(2/(n - 1» (y(Xl) + ~ «y(x/) - ao)Cj» and
j=2
n-l
b, =(2/(n - 1» ~ «y(Xj) - ao)S/) where
/=2

Cj = cos(2rrr(j - 1)/(n - 1» and S/ = sin(2rrr(j -1)/(n - 1»


To reduce computing time, Sj and Cj are stored in arrays for further use and
the following trigonometric identities are employed in their computation:
sin(21rrj/(n - 1» = sin(2rrrU - 1)/(n - 1»cos(2rrT/(n - 1» +
cos(2rrrU - 1)/(n - 1»sin(2rrr/(n - 1» and
cos(21rrj/(n - 1» = cos(2rrrU - 1)/(n - 1)cos(2rrr/(n - 1) -
sin(2rrrU - 1)/(n - 1»sin(21Tr/(n - 1»
Output arrays A( ) and B( ) are used to store the coefficients a, and b, respec-
tively, such that A(l) = ao, A(2) = al, A(3) = a2, ... and similarly B(1) = b o,
B(2) = b l , B(3) = b 2 , ••••
134 Advanced BASIC Scientific Subroutines

2000 REM FOURIER ANALYSIS


2010 REM
2020 REM SUBROUTINE: FURIER
2030 REM
2040 REM APPROXIMATES A PERIODIC FUNCTION Y(X) DE-
2050 REM SCRIBED BY N EQUALLY-SPACED DATA POINTS WITH
2060 REM A FINITE lo'OURIER SERIES F(X) OF' A FORM: AO
2070 REM + A1.COS(1.K) + B1.SIN(1.K) + A2.COS(2.K)
2080 REM + B2.SIN(2.K) + . . WHERE K = 2.PI.X/(N - 1)
2090 REM AND N-1 IS THE PERIOD OF Y(X)
2100 REM
2110 REM VARIABLES:
2120 REM INPUT:
2130 REM D() ..... ARRAY OF OBSERVED DATA; THE FIRST
2140 REM AND LAST DATA POINTS MUST BE EQUAL
2150 REM NHRMC ... HIGHEST HARMONIC TO BE COMPUTED
2160 REM NUMDAT .. NUMBER OF DATA POINTS
2170 REM OUTPUT:
2180 REM A() ..... ARRAY OF COEFFICIENTS OF COSINE
2190 REM TERMS, A(l) = AO, A(2) = A1, ....
2200 REM B() ..... ARRAY OF COEFFICIENTS OF SINE
2210 REM TERMS, B(l) = 0, B(2) = B1, ....
2220 REM F() ..... CALCULATED VALUES OF FUNCTION Y(X)
2230 REM LOCAL: ... C(), C1, P, Q, SCI, SIGMAA,
2240 REM SIGMAB, V1
2250 REM
2260 REM ARRAY DIMENSIONS:
2270 REM A(), B() . . . . . . . . . . . . . (NHRMC + 1)
2280 REM C(), D(), Io'(), S() ... (NUMDAT)
2290 REM
2300 REM CHECK INPUT DATA
2310 LET VI = NUMDAT - 1
2320 IF NHRMC > V1/2 OR NUMDAT < 3 THEN GOTO 2780
2330 IF 0(1) <> D(NUMDAT) THEN GO TO 2820
2340 REM
2350 REM COMPUTE AVERAGE LEVEL AND FIND A(l) AND B(l)
2360 LET SIGMAA = 0(1)
2370 FOR P = 2 TO V1
2380 LET SIGMAA = D(P) + SIGMAA
2390 NEXT P
2400 LET A(l) = SIGMAA/V1
2410 LET B(l) = 0
2420 REM
2430 REM SET INITIAL VALUE OF ARRAY OF APPROX. VALUES
2440 FOR P = 1 TO NUMDAT
2450 F(P) = A(l)
2460 NEXT P
2470 IF NHRMC < 1 THEN GO TO 2760
2480 REM
2490 REM COMPUTE SINE AND COSINE TERMS
2500 LET C1 = 6.28318531/V1
2510 FOR P = 1 TO NHRMC
2520 LET S(2) = SIN(C1*P)
2530 LET C(2) = COS(C1*P)
2540 FOR Q = 3 TO VI
2550 LET SeQ) seQ - 1)*C(2) + C(Q - 1)*S(2)
2560 LET C(Q) = C(Q - 1)*C(2) - seQ - 1)*S(2)
2570 NEXT Q
The Subroutines 135

Subroutine Listing

2580 REM
2590 REM COMPUTE FOURIER COEFFICIENTS
2600 LET SIGMAA = D(l) - A(l)
2610 LET SIGMAB = 0
2620 FOR 0 = 2 TO V1
2630 SIGMAA SIGMAA + (D(O) - A(l»*C(Q)
2640 SIGMAB = SIGMAB + (0(0) - A(l»*S(Q)
2650 NEXT 0
2660 LET A(P + 1) 2*SIGMAA/V1
2610 LET B(P + 1) 2*SIGMAB/V1
2680 REM
2690 REM COMPUTE DATA POINTS FROM FOURIER APPROX.
2100 F(l) = F(l) + A(P + 1)
2110 FOR 0 = 2 '1'0 NUMDA'I'
2120 F(Q) = F(Q) + A(P + l)*C(Q) + B(P + l)*S(Q)
2130 NEXT 0
2140 NEXT P
2150 LET F(NUMDAT) F(l)
2160 REM
2110 RETURN
2180 REM
2190 PRINT " NO. HARMONICS TOO HIGH OR NUMDA'r INVALID"
2800 PRINT" NHRMC = "; NHRMC; ", NUMDAT = "; NUMOAT
2810 END
2820 REM
2830 PRINT" FIRS'r AND LAST DATA POINTS NOT EQUAL,"
2840 PRINT" FIRST AND LAST DATA: "; D(l), D(NUMDAT)
2850 END

Sample Program

A transducer is attached to a machine to assess vibration. When the machine is


operated the transducer produces a signal which has a period of 15 seconds. The
readings at time t, which are recorded at one second intervals, are displayed in
the table below.

time 0 1 2 3 4 5 6 7 8
sig. 15.5 20.5 4.69 9.09 16.5 5.4 9.31 11.8 -2.02

time 9 10 11 12 13 14 15 16 17
sig. 4.61 10.6 -3.54 1.48 10.9 5.16 15.5 20.5 4.69

Approximate the signal by a Fourier series. Use the first sixteen observations
to determine the Fourier coefficients as far as the sixth harmonic.
136 Advanced BASIC Scientific Subroutines

1000 REM SAMPLE PROGRAM: PFURIER


1010 REM
1020 REM FITS A FOURIER SERIES TO A SET OF DATA
1030 REM
1040 REM ARRAY DIMENSIGNS:
1050 DIM A(7)
1060 DIM B(7)
1070 DIM C(16)
1080 DIM D(16)
1090 DIM F(16)
1100 DIM S(16)
1110 REM
1120 DATA 15.5, 20.5. 4.69. 9.09. 16.5. 5.4. 9.31
1130 DATA 11.8. -2.02. 4.61. 10.6. -3.54. 1.48. 10.9
1140 DATA 5.16. 15.5
1150 REM
1160 REM SET INITIAL VALUES AND READ DATA
1170 LET NUMDAT = 16
1180 LET NHRMC = 6
1190 FOR I = 1 TO NUMDAT
1200 READ D(I)
1210 NEXT I
1220 REM
1230 REM COMPUTE COEFFICIENTS AND PRINT RESULTS
1240 REM CALL SUBROUTINE FURIER
1250 GOSUB 2000
1260 PRINT " FOURIER COEFFICIENTS"
1270 PRINT
1280 PRINT" HARMONIC"." AR". " BR"
1290 FOR I 1 TO NHRMC + 1
1300 PRINT I - 1. A(I). B(I)
1310 NEXT I
1320 PRINT
1330 PRINT " FOURIER APPROXIMATION"
1340 PRINT
1350 PRINT " OBS.". " OBSERVED". " COMPUTED"
1360 PRINT " NUMBER", " SIGNAL". " SIGNAL"
1370 FOR I = 1 TO NUMDAT
1380 PRINT I, D(I), F(I)
1390 NEXT I
1400 END
>RUN
FOURIER COEFFICIENTS

HARMONIC AR BR
o 7.999 o
1 2.994 3.99
2 2.006 -7.65E-3
3 2.488 5.96E-9
4 -5.744E-3 -1.008E-2
5 -6.667E-4 6.999
6 1. 338E-2 2.409E-8

FOURIER APPROXIMATION
The Subroutines 137

OBS. OBSERVED COMPUTED


NUMBER SIGNAL SIGNAL
1 15.5 15.49
2 20.5 20.5
3 4.69 4.688
4 9.09 9.089
5 16.5 16.5
6 5.4 5.395
7 9.31 9.317
8 11.8 11. 79
9 -2.02 -2.011
10 4.61 4.6
11 10.6 10.61
12 -3.54 -3.55
13 1. 48 1. 49
14 10.9 10.89
15 5.16 5.167
16 15.5 15.49

The computed results indicate that the waveform may be approximated by


the expression
8 + 3cos k + 4sin k + 2cos 2k + 2.5cos 3k + 7sin 5k
where k = (2rrt)/ 15, if coefficients < 0.02 are neglected. The computed comparison
of the full series against the input data indicates a good fit and it is unlikely that
there are any significant harmonics above the 5th present in the signal.

Notes

1. The subroutine performs some checks on the input data and the program will
be interrupted and a warning issued:
(a) If the number of harmonics to be computed is too high for the available data;
that is, ifNHMRMC > (NUMDAT - 1)/2.
(b) If the first and last data points are not equal.
(c) If fewer than three items of data are available.
2. A value for NHRMC of zero or less will cause the mean value of the function
to be computed and stored in A(1).
3. Bajpai et al. (1974) and Hamming (1962) are suggested for further reading.
138 Advanced BASIC Scientific Subroutines

2.9 Calculus

SOLUTION OF FIRST-ORDER AND SECOND-ORDER DIFFERENTIAL


EQUATIONS

Subroutines: DIFEQI and DIFEQ2

Description

Numerical solution of ordinary first-order atld second-order differential equations


by the Runge-Kutta method.

Method

1. The Runge-Kutta method for a jirst-order differential equation. Given an initial


value equation
Y' = f(x,y), y(xo) = Yo
theny(xo + nH) is to be found for a fIxed step Hwhere n =0,1,2,3, .... This
is obtained by fIrst calculating, in order, the following quantities:

K1 =H.f(xn,Yn)
Kz =H.f(xn +H/2,Yn +K 1/2)
K3 =H.f(xn + H/2,Yn + Kz/2)
K4 =H.f(xn +H,Yn +K3)
and then using the recursion formula

Yn+1 =Yn +(K1 + 2Kz + 2K3 + K4)/6


2. The Runge-Kutta method for a second order differential equation. Given
y" = f(x, y,y')
and
Yo = f(xo) , y'(xo) = Zo
thenYn+l is to be found for a fIxed step Hand n = 0, 1,2, ...
=
Lety' f(x,y, z) and z' =g(x,y, z), then

Yn+1 =Yn + (Kl + 2Kz + 2K3 + K4)/6 and


Zn+l =Zn + (L1 + 2L z + 2L3 + L 4 )/6
where

Kl =H.f(xn ,Yn, zn)


Ll =H.g(xn,Yn,zn)
The Subroutines 139

Kz = Hf(x n +H/2,Yn +Kl/2,zn +L 1 /2)


L2 =H.g(xn +H/2,Yn +Kl/2,zn +Ld2)
K3 =Hf(x n +H/2,Yn +K2/2,zn +L 2 /2)
L3 =H.g(xn +H/2,Yn + K 2/2,zn +L 2/2)
K4 =H.f(xn +H,Yn +K3 , Zn+ L 3)
L4 =H.g(xn +H,Yn +K3,Zn +L3)
Now let
Y' =Z =f(x,y)
then
y"= z' =g(x,y,y').
Substituting in the above equations:

Kl =H.y~
Ll =Hg(xn,Yn, zn)
K2 = H.(y~ + Ld2)
L2 =H.g(xn + H/2,Yn + K 1/2, zn + Ld2)
K3 = H(y~ + L2/2)
L3 = Hg(x n + H/2,Yn + K 2/2, zn + L2/2)
K4 = H.(y~ + L 3)
L4 =H.g(xn +H,Yn +K3,Zn +L3)
and Y n +1 = Yn + (Kl + 2K2 + 2K3 + K 4)/6
Y~+1 = y~ + (Ll + 2L2 + 2L3 + L 4)/6

Subroutine Listings

DIFEQ1

2000 REM SOLU OF 1ST ORDER DIFFERENTIAL EQUS


2010 REM
2020 REM SUBROUTINE: DIFEQ1
2030 REM
2040 REM SOLVES ORDINARY FIRST-ORDER DIFFERENTIAL
2050 REM EQUATIONS Y' = F(X,Y) BY RUNGE-KUTTA METHOD
2060 REM
2070 REM VARIABLES:
2080 REM INPUT:
2090 REM F(X,Y) .. DIFFERENTIAL EQUATION DEFINED IN
2100 REM MAIN PROGRAM BY DEF FN STATEMENT
2110 REM H .•..... STEP SIZE OF X
2120 REM NUMSTP .. NUMBER OF STEPS
2130 REM XO ...... INITIAL VALUE OF X
2140 REM YO ...... INITIAL VALUE OF Y
2150 REM OUTPUT:
2160 REM A() ..... ARRAY CONTAINING VALUES OF X
140 Advanced BASIC Scientific Subroutines

2170 REM B() ..... ARRAY CONTAINING VALUES OF Y


2180 REM C() ..... ARRAY CONTAINING VALUES OF Y'
2190 REM LOCAL: ... K1, K2, K3, K4, P, X, Y
2200 REM ARRAY DIMENSIONS:
2210 REM A(), B(), C(): .. (NUMSTP + 1)
2220 REM
2230 REM SET INITIAL VALUES AND FIND Y AT EACH STEP
2240 LET B(l) = YO
2250 FOR P = 1 TO NUMSTP
2260 LET A(P) = XO + (P - l)*H
2270 LET X = A(P)
2280 LET Y = B(P)
2290 LET C(P) = FNF(X,Y)
2300 LET K1 = H*C(P)
2310 LET X = A(P) + 0.5*H
2320 LET Y = B(P) + 0.5*K1
2330 LET K2 = H*FNF(X,Y)
2340 LET Y = B(P) + 0.5*K2
2350 LET K3 = H*FNF(X,Y)
2360 LET X = A(P) + H
2370 LET Y = B(P) + K3
2380 LET K4 = (K1 + 2*K2 + 2*K3 + H*FNF(X,Y»/6
2390 LET B(P + 1) B(P) + K4
2400 NEXT P
2410 RETURN

DIFEQ2

2000 REM SOLU OF 2ND ORDER DIFFERENTIAL EQUS


2010 REM
2020 REM SUBROUTINE: DIFEQ2
2030 REM
2040 REM SOLVES ORDINARY SECOND-ORDER DH"F'ERENTIAL
2050 REM EQUS Y" = F(X,Y,Y') BY RUNGE-KUTTA METHOD
2060 REM
2070 REM VARIABLES:
2080 REM INPUT:
2090 REM F(X,Y,Z) •. DIFFERENTIAL EQUATION DEFINED IN
2100 REM MAIN PROGRAM BY DEF FN STATEMENT
2110 REM H ....... STEP SIZE OF X
2120 REM NUMSTP .. NUMBER OF STEPS
2130 REM XO ...... INITIAL VALUE OF X
2140 REM YO ...... VALUE OF Y AT XO
2150 REM ZO ...... VALUE OF Y' AT XO
2160 REM OUTPUT:
2170 REM A() ..... ARRAY CONTAINING VALUES OF X
2180 REM B() ..... ARRAY CONTAINING VALUES OF Y
2190 REM C() ..... ARRAY CONTAINING VALUES OF Y'
2200 REM LOCAL: ... L1, L2, L3, L4, K1, K2, K3, K4
2210 REM P, X, Y
2220 REM ARRAY DIMENSIONS:
2230 REM A(), B(), C(): .. (NUMSTP + 1)
2240 REM
The Subroutines 141

2250 REM SET INITIAL VALUES AND FIND Y AT EACH STEP


2260 LET B(l) = YO
2270 LET C(l) = ZO
2280 FOR P = 1 TO NUMSTP
2290 LET A(P) = xo + (P - l)*H
2300 LET X A(P)
2310 LET Y = B(P)
2320 LET Z = C(P)
2330 LET K1 = H*C(P)
2340 LET Ll = H*FNF(X,Y,Z)
2350 LET X A(P) + 0.5*H
2360 LET Y = B(P) + 0.S*K1
2370 LET Z = C(P) + 0.S*L1
2380 LET K2 = H*(C(P) + 0.S*L1)
2390 LET L2 = H*FNF(X,Y,Z)
2400 LET Y = B(P) + 0.S*K2
2410 LET Z = C(P) + 0.S+L2
2420 LET K3 = H*(C(P) + 0.S*L2)
2430 LET L3 = H*FNF(X,Y,Z)
2440 LET X A(P) + H
2450 LET Y = B(P) + K3
2460 LET Z = C(P) + L3
2470 LET K4 = (K1 + 2*K2 + 2*K3 + H*(C(P) + L3»/6
2480 LET L4 = H*FNF(X,Y,Z)
2490 LET B(P + 1) = B(P) + K4
2500 LET C(P+1) = C(P) + (L1 + 2*L2 + 2*L3 + L4)/6
2510 NEXT P
2520 RETURN

Sample Programs

1. Solve y' =(6x 2 - 4xy)/(2x 2 + 1) wheny(O) =0 with step size = 1/32 and
number of steps = 13.
Also evaluate v = 2x 3 /( 1 + 2X2) for the same number of steps. Compare these
two results.

1000 REM SAMPLE PROGRAM: PDIFEQ1


1010 REM
1020 REM SOLVES ORDINARY FIRST-ORDER DIFFERENTIAL
1030 REM EQUATIONS BY A NUMERICAL METHOD
1040 REM
10S0 REM VARIABLES:
1060 REM V( X) .... THE FUNCTION OF X
1070 REM
1080 REM DEFINE DIFFERENTIAL EQUATION 'ro BE SOLVED
1090 DEF FNF(X,Y) = (6*X*X - 4*X*Y)/(2*X*X + 1 )
1100 REM
1110 REM DEFINE FUNCTION TO BE EVALUATED
1120 DEF FNV(X) = 2*X*X*X/(1 + 2*X*X)
1130 REM
1140 REM ARRAY DIMENSIONS:
142 Advanced BASIC Scientific Subroutines

1150 DIM A(14)


1160 DIM B(14)
1170 DIM C(14 )
1180 REM
1190 REM INITIALISE VARIABLES
1200 LET XO = 0
1210 LET YO = 0
1220 LET H = 1/32
1230 LET NUMSTP = 13
1240 REM
1250 REM EVALUATE AND PRINT RESULTS
1260 REM CALL SUBROUTINE DIFEQ1
1270 GOSUB 2000
1280 PRINT " X", " yin,
" Y(X)";
1290 PRINT " V(X)"
1300 FOR I = 1 TO NUMSTP
1310 LET X = A( I)
1320 PRINT A( I), C( I), B (I) , FNV(X)
1330 NEXT I
1340 END

>RUN
X Y' Y(X) vex)
0 0 0 0
3.125E-2 5.8403535E-3 6.0916187E-5 6.0916179E-5
6.25E-2 2.3135629E-2 4.8449624E-4 4.8449612E-4
9.375E-2 5.1226602E-2 1.6194822E-3 1. 6194818E-3
0.125 8.9072543E-2 3.7878798E-3 3.7878788E-3
0.15625 0.13533008 7.2742105E-3 7.2742086E-3
0.1875 0.18844904 1.2317521E-2 1. 2317518E-2
0.21875 0.24677412 1.910651lE-2 1.9106506E-2
0.25 0.30864197 2.7777784E-2 2.7777778E-2
0.28125 0.37246515 3.8416956E-2 3.8416948E-2
0.3125 0.4367978 5.1062102E-2 5.1062092E-2
0.34375 0.50038058 6.5708938E-2 6.5708926E-2
0.375 0.56216536 8.2317087E-2 8.2317073E-2

From the computer printout it can be seen thaty(x) is equal to vex) for six signi-
ficant figures. In fact, vex) is the exact solution of the given differential equation
y'(x).
2. Solve the second-order equationy" = 2y 3 wheny(1) = 1 andy'(l) = 1 with
step size = 1/32 and 33 steps. Also evaluate v = 1/x for the same step values and
compare the results.

1000 REM SAMPLE PROGRAM: PDIFEQ2


1010 REM
1020 REM SOLVES ORDINARY SECOND-ORDER DIFFERENTIAL
1030 REM EQUATIONS BY A NUMERICAL METHOD
1040 REM
1050 REM VARIABLES:
1060 REM V(X) ..... THE FUNCTION OF X
The Subroutines 143

1070 REM
1080 REM DEFINE DIFFERENTIAL EQUATION TO BE SOLVED
1090 DEF FNF(X,Y,Z) = 2*Y 3 A

1100 REM
1110 REM DEFINE FUNCTION TO BE EVALUATED
1120 DEF FNV(X) = l/X
1130 REM
1140 REM ARRAY DIMENSIONS:
1150 DIM A( 34)
1160 DIM B(34)
1170 DIM C(34)
1180 REM
1190 REM INITIALISE VARIABLES
1200 LET XO = 1
1210 LET YO = 1
1220 LET ZO = -1
1230 LET H = 1/32
1240 LET NUMSTP = 33
1250 REM
1260 REM EVALUATE AND PRINT RESULTS
1270 REM CALL SUBROUTINE DIFEQ2
1280 GOSUB 2000
1290 PRINT" X", " yll', " YIX)";
1300 PRINT" V(X)"
1310 FOR I = 1 TO NUMSTP
1320 LET X = A(I)
1330 PRINT A(I), C(I), B(I), FNVIX)
1340 NEXT I
1350 END

>RUN
X Y' Y(X) V(X)
1 -1 1 1
1.03125 -0.9403122 0.96969698 0.96969697
1.0625 -0.88581312 0.94117649 0.94117647
1.09375 -0.83591833 0.91428575 0.91428571
1.125 -0.7901234 0.88888893 0.88888889
1.15625 -0.74799117 0.86486491 0.86486486
1.1875 -0.7091412 0.84210532 0.84210526
1. 21875 -0.6732412 0.82051288 0.82051282
1. 25 -0.6399999 0.80000007 0.8
1. 28125 -0.6091611 0.78048788 0.7804878
1.3125 -0.58049874 0.76190484 0.76190476
1.34375 -0.55381274 0.74418613 0.74418605
1. 375 -0.52892547 0.72727282 0.72727273
1.40625 -0.50567886 0.71111121 0.71111111
1. 4375 -0.48393178 0.69565228 0.6956'5217
1.46875 -0.46355799 0.68085118 0.68085106
1.5 -0.44444426 0.66666679 0.66666667
1. 53125 -0.42648876 0.65306135 0.65306122
1. 5625 -0.40959979 0.64000013 0.64
1.59375 -0.39369451 0.62745112 0.62745098
1. 625 -0.37869799 0.61538477 0.61538462
1.65625 -0.3645423 0.60377374 0.60377358
144 Advanced BASIC Scientific Subroutines

1. 6875 -0.35116572 0.59259276 0.59259259


1. 71875 -0.33851213 0.58181836 0.58181818
1. 75 -0.32653033 0.57142876 0.57142857
1. 78125 -0.31517361 0.5614037 0.56140351
1.8125 -0.30439922 0.55172434 0.55172414
1. 84375 -0.29416803 0.5423731 0.54237288
1. 875 -0.28444412 0.53333356 0.53333333
1.90625 -0.2751945 0.5245904 0.52459016
1. 9 37 5 -0.26638883 0.51612928 0.51612903
1.96875 -0.25799913 0.50793676 0.50793651
2 -0.24999962 0.50000027 0.5

Again it can be seen by comparing values of y(x) and v(x) that y(x) is equal to
v(x) to six significant figures and v(x) is the exact solution ofy"(x).

Notes

1. The Runge-Kutta methods do not provide information on the accuracy achieved


and therefore the user has to make an informed choice of H. The rule of thumb is
to start with a large step size and repeat with half the step size and then compare
the results for consistency.
2. Hamming (1962), Conte (1965), Froberg (1970) and Kreyszig (1983) are
recommended for further reading.
The Subroutines 145

NUMERICAL INTEGRATION OF A POLYNOMIAL BY THE TRAPEZIUM RULE


AND SIMPSON'S RULE, AND INTEGRATION OF DATA BY SIMPSON'S RULE

Subroutines: TRPZDL, SIMPSN,INTDAT

Description

Numerical evaluation of a defin~te integral of an analytical function by the


methods of the trapezium rule and Simpson's rule. Integration of a function
described by a set of discrete data by Simpson's rule.

Method

1. Trapezium rule. This method divides the area bounded by the limits A and B
into a number of trapezia each of width H. Summing the areas of trapezia gives

I A
B
F(x)dx ~ H/2 [{F(A) + F(B)} +
2{F(A +9) +F(A + 2H) + ... +F(A +(N - 2)H)}]
where
H =(B - A )/(N - I) and N = number of ordinates
A =lower limit and B = upper limit.
2. Simpson's rule. This method divides the area bounded by the limits into an
even number of parallel strips of width H, and approximates the area of pairs of
strips using parabolas. Thus

fA
B
F(x)dx ~ H/3 [{F(A) + F(B)} +
4{F(A + H) + F(A + 3H) + ... + F(A + (N - 2)H)} +
2{F(A + 2H) + F(A + 4H) + ... +F(A + (N - 3)H)}]
where
H= (B -A)/(N - 1) and
N = number of ordinates which should be an odd integer.
3. Discrete data set. If the function F(x) is defmed by a set of discrete data
Yt = Y(Xi) at a set of ordinates xi (i = 1, 2, ... ,N) spaced at distance H, then by
Simpson's rule

f B=XN

A-Xl
_ F(x)dx ~H/3 [(yt + YN) + 4(yz + Y4 + ... +YN -1)
+2(Y3+YS + ... +YN-Z)]
where N = number of data points which should be an odd integer.

Subroutines Listings
146 Advanced BASIC Scientific Subroutines

TRPZDL and SIMPSN

2000 REM NUMERICAL INTEGRATION


2010 REM
2020 REM SUBROUTINE: TRPZDL
2030 REM
2040 REM NUMERICAL INTEGRATION OF A POLYNOMIAL BY
2050 REM THE TRAPEZIUM RULE
2060 REM
2070 REM VARIABLES:
2080 REM INPUT:
2090 REM A....... LOw~R LIMIT OF INTEGRATION
2100 REM B ....... UPPER LIMIT OF INTEGRATION
2110 REM NORD .. NUMBER OF ORDINATES
2120 REM Y(X) .... FUNCTION TO BE INTEGRATED, DEFINED
2130 REM IN MAIN PROGRAM BY DEF FN
2140 REM OUTPUT:
2150 REM SIGMA ... VALUE OF INTEGRAL
2160 REM LOCAL: ... H, P, X
2170 REM
2180 REM CHECK VALIDITY OF LIMITS
2190 IF INT(NORD) < NORD OR NORD <= 1 THEN GOTO 2350
2200 IF A > B THEN GOTO 2390
2210 REM
2220 REM SET INITIAL VALUES AND COMPUTE INTEGRAL
2230 LET
H = (B - A)/(NORD - 1)
2240 X =B
LET
2250 LET
SIGMA FNY(X)
2260 LET
X = A
2270 SIGMA
LET SIGMA + FNY(X)
2280 X = X + H
LET
2290 P = 2 TO NORD - 1
FOR
2300 LET SIGMA = SIGMA + 2*FNY(X)
2310 LET X = X + H
2320 NEXT P
2330 LET SIGMA = 0.5*SIGMA*H
2340 RETURN
2350 REM
2360 PRINT " INPUT ERROR: NORD SHOULD BE"
2370 PRINT" AN INTEGER> 1, NORD "i NORD
2380 END
2390 REM
2400 PRINT" INPUT ERROR: CHECK A > B"
2410 PRINT" A = "i Ai ", B = "i B
2420 END
3000 REM NUMERICAL INTEGRATION
3010 REM
3020 REM SUBROUTINE: SIMPSN
3030 REM
3040 REM NUMERICAL INTEGRATION OF A POLYNOMIAL BY
3050 REM SIMPSON'S RULE
3060 REM
3070 REM VARIABLES:
3080 REM INPUT:
The Subroutines 147

3090 REM A •••..•• LOWER LIMIT OF INTEGRATION


3100 REM B •..••.. UPPER LIMIT OF INTEGRATION
3110 REM NORD ...• NUMBER OF ORDINATES = ODD INTEGER
3120 REM Y(X) •..• FUNCTION TO BE INTEGRATED, DEFINED
3130 REM IN MAIN PROGRAM BY DEF FN
3140 REM OUTPUT:
3150 REM SIGMA •.• VALUE OF INTEGRAL
3160 REM LOCAL: .•• H, P, X
3170 REM
3180 REM CHECK VALIDITY OF INPUT DATA
3190 IF INT(NORD) <> NORD OR NORD <= 1 THEN GOTO 3430
3200 IF NORD/2 = INT(NORD/2) THEN GOTO 3430
3210 IF A > B THEN GOTO 3470
3220 REM
3230 REM SET INITIAL VALUES AND COMPUTE INTEGRAL
3240 LET SIGMA = 0
3250 LET H = (B - A)/(NORD - 1)
3260 LET X = B
3270 LET SIGMA = FNY(X)
3280 LET X = B - H
3290 LET SIGMA = SIGMA + 4*FNY(X)
3300 LET X = A
3310 LET SIGMA SIGMA + FNY(X)
3320 LET X = X + H
3330 IF NORD = 3 THEN GOTO 3400
3340 FOR P = 2 TO NORD - 3 STEP 2
3350 LET SIGMA SIGMA + 4*FNY(X)
3360 LET X = X + H
3370 LET SIGMA = SIGMA + 2*FNY(X)
3380 LET X X + H
3390 NEXT P
3400 REM
3410 LET SIGMA = SIGMA*H/3
3420 RETURN
3430 REM
3440 PRINT " INPUT ERROR: NORD SHOULD BE"
3450 PRINT" AN ODD INTEGER> 1, NORD = "; NORD
3460 END
3470 REM
3480 PRINT " INPUT ERROR: CHECK A > B"
3490 PRINT" A = "; A; ", B = "; B
3500 END

/NTDAT

2000 REM NUMERICAL INTEGRATION


2010 REM
2020 REM SUBROUTINE: INTDAT
2030 REM
2040 REM NUMERICAL INTEGRATION BY SIMPSON'S RULE OF
2050 REM A FUNCTION DEFINED BY A SET OF DISCRETE DATA
2060 REM
2070 REM VARIABLES:
148 Advanced BASIC Scientific Subroutines

2080 REM INPUT:


2090 REM H.•..... DISTANCE BETWEEN ORDINATES
2100 REM NORD .... NUMBER OF ORDINATES = ODD INTEGER
2110 REM Y() ..... SET OF Y-COORDINATES
2120 REM OUTPUT:
2130 REM SIGMA ... VALUE OF INTEGRAL
2140 REM LOCAL ...• P
2150 REM ARRAY DIMENSIONS:
2160 REM Y() ...•• (NORD)
2170 REM
2180 REM CHECK VALIDITY OF INPUT DATA
2190 IF INT(NORD) <> NORD OR NORD <= 1 THEN GOTO 2310
2200 IF NORD/2 = INT(NORD/2) THEN GO TO 2310
2210 REM
2220 REM COMPUTE INTEGRAL
2230 LET SIGMA = Y(l) + 4*Y(NORD - 1) + Y(NORD)
2240 IF NORD = 3 THEN GOTO 2280
2250 FOR P = 2 TO NORD - 3 STEP 2
2260 LET SIGMA = SIGMA + 4*Y(P) + 2*Y(P + 1)
2270 NEXT P
2280 REM
2290 LET SIGMA = SIGMA*H/3
2300 RETURN
2310 REM
2320 PRINT" INPUT ERROR: NORD SHOULD BE"
2330 PRINT" AN ODD INTEGER> 1, NORD "; NORD
2340 END

Sample Programs

1. (a) Use the trapezium rule with 100 ordinates to estimate

f:sinx~
(b) Repeat the exercise by using Simpson's rule with 19 ordinates.

1000 REM SAMPLE PROGRAM: PTRPZDL


1010 REM
1020 REM INTEGRATION BY 'l'RAPEZIUM AND SIMPSON'S
1030 REM RULES. REQUIRES SUBROUTINES TRPZDL, SIMPSN
1040 REM
1050 REM DEFINE FUNCTION TO BE IN'rEGRATED
1060 DEF FNY(X) = SIN(X)
1070 REM
1080 REM INITIALISE VARIABLES
1090 LET A 0
1100 LET B = 3.14159256
1110 REM
1120 REM INTEGRA'l'E BY TRAPEZIUM RULE
1130 REM CALL SUBROUTINE TRPZDL
The Subroutines 149

1140 LET NORD = 100


1150 GOSUB 2000
1160 PRINT " INTEGRAL BY TRAPEZIUM METHOD " ,. SIGMA
1170 REM
1180 REM INTEGRATE BY SIMPSON'S RULE
1190 REM CALL SUBROUTINE SIMPSN
1200 LET NORD = 19
1210 GOSUB 3000
1220 PRINT
1230 PRINT " INTEGRAL BY SIMPSON'S METHOD " ,. SIGMA
1240 END

>RUN
INTEGRAL BY TRAPEZIUM METHOD 1. 9998322

INTEGRAL BY SIMPSON'S METHOD 2.0000103

The exact value of the integral is 2. It can be seen from this example that
Simpson's rule provides a better approximation than does the trapezium rule, and
with fewer subdivisions. A disadvantage of Simpson's rule is the requirement for an
even number of steps; this is not a condition for the use of the trapezium rule.
A major limitation of both methods is the need to specify uniform intervals.
Caution should be exercised when integrating functions which exhibit widely
different rates of change over the range of interest.
2. A continuous functionf(x) is defmed by the table below:
x 0 0.30 0.60 0.90 1.20 1.50 1.80
f(x) 2.72 3.00 3.32 3.69 4.06 4.48 4.95
Use Simpson's rule to estimate

f:· S
f(x) dx

1000 REM SAMPLE PROGRAM: PINTDAT


1010 REM
1020 REM INTEGRATION OF A FUNCTION DEFINED BY A
1030 REM SET OF EQUALLY-SPACED DISCRETE DATA
1040 REM
1050 REM ARRAY DIMENSIONS:
1060 DIM Y(7)
1070 DATA 2.72, 3, 3.32, 3.69, 4. 06, 4.48, 4.95
1080 REM
1090 REM SET INITIAL VALUES
1100 LET NORD = 7
1110 LET H = 0.3
1120 REM
1130 REM READ DATA
1140 FOR I = 1 TO NORD
1150 READ Y(I)
150 Advanced BASIC Scientific Subroutines

1160 NEXT I
1170 REM
1180 REM EVALUATE INTEGRAL
1190 REM CALL SUBROUTINE INTDAT
1200 GOSUB 2000
1210 PRINT " RESULT OF INTEGRATION "; SIGMA
1220 END

>RUN
RESULT OF INTEGRATION = 6.711

The value of the integral is 6.71 to two places of decimals. The above example shows
a useful method of integrating in cases where we only know the ordinates, and not
the function that describes the relation.

Notes

1. A check for input data is made in the subroutines and the main program is
terminated if
(a) the range is incorrectly stated - that is, if the lower limit of integration is
greater than the upper limit,
(b) the number of ordinates is not an odd integer for Simpson's method.
2. The error of the trapezium rule approximation is
- (B _A).H2 f"(c)/12 A<c<B
and for Simpson's method is
- (B -A).H4 f'"'(c)/180 A<c<B
The subroutines do not calculate these error terms. In practice the rule of thumb
applied for determining the accuracy of the result is to re-run the program with
approximately double the number of ordinates than before and then compare the
results. However, note that if the width H gets too small, then the error tends to
increase because of rounding errors.
3. Conte (1965) and Mason (1983) are suggested for further reading.
The Subroutines 151

2.10 Solution of Equations

SOLUTION OF N LINEAR EQUATIONS WITH N UNKNOWNS

Subroutine: SOLUTN

Description

Solves a system of N linear equations in N unknowns by the method of Gauss


elimination with pivoting.
Requires subroutine MATDET.

Method

A system of N linear equations in N unknowns can be represented by the matrix


equation A. X = B where A is the matrix of the coefficients of the unknowns con·
tained in the matrix X, and B is the matrix of constants. Such a system of equations
may be solved by the 'Gauss·elimination' method with pivotal condensation as
described in the section on matrix inversion.
The adjoined or augmented matrix A IB is located in the array A(). If A is of
the order n x nand B is n x r, then the dimensions of the array A( ) are
n X (n + r). The subroutine uses subroutine MATDET which reduces matrix A
to an upper·triangular matrix. The unknowns are computed in the reverse order
by back·substitution.
The solution matrix is transferred back into array A( ) and thus the first
n x r rows and columns of the array A( ) contain the solution matrix.

Subroutine Listing
2000 REM SOLVES N LINEAR EQUATIONS WITH N UNKNOWNS
2010 REM
2020 REM SUBROUTINE: SOLUTN
2030 REM
2040 REM SOLVES SYSTEMS OF LINEAR EQUATIONS OF FORM
2050 REM A*X = B BY GAUSS ELIMINATION WITH PIVOTING
2060 REM REQUIRES SUBROUTINE MATDET
2070 REM VARIABLES:
2080 REM INPUT:
2090 REM A() ..... LOCATION MATRIX FOR AIB .•. COEFF.
2100 REM MATRIX- ADJOINED WITH CONST. MATRIX
2110 REM MCOL .... MAXIMUM NUMBER OF COLUMNS IN A
2120 REM (ODR + NO. OF SYSTEMS TO SOLVE)
2130 REM ODR ..... ORDER OF COEFFICIENTS MA'l'RIX A
2140 REM OUTPUT:
2150 REM A() ..... THE ORIGINAL MATRIX IS OVERWRITTEN
2160 REM BY THE SOLUTION MATRIX
2170 REM LOCAL .... MDET, P,Q,R,W()
2180 REM ARRAY DIMENSIONS:
152 Advanced BASIC Scientific Subroutines

2190 REM A() ..... (ODR, ODR + NUMBER OF SYSTEMS)


2200 REM W( ) ..•.. (ODR + 1)
2210 REM
2220 REM CALL SUBROUTINE MATDET
2230 GOSUB 3000
2240 IF MDET = 0 THEN GO TO 2470
2250 REM
2260 REM BACK SUBSTITUTION
2270 FOR P = ODR + 1 TO MCOL
2280 FOR Q = ODR TO 1 STEP -1
2290 LET W(Q) = A(Q,P)
2300 IF Q = P THEN GOTO 2340
2310 FOR R = Q + 1 TO ODR
2320 LET W(Q) = W(Q) - W(R)*A(Q,R)
2330 NEXT R
2340 REM
2350 LET W(Q) = W(Q)/A(Q,Q)
2360 NEXT Q
2370 FOR R = 1 TO ODR
2380 LET A(R,P) = W(R)
2390 NEXT R
2400 NEXT P
2410 FOR P = 1 TO ODR
2420 FOR Q = 1 TO MCOL - ODR
2430 LET A(P,Q) = A(P,ODR + Q)
2440 NEXT Q
2450 NEXT P
2460 RETURN
2470 REM
2480 PRINT" NO SOLUTION FOUND; MATRIX A IS SINGULAR"
2490 END

Sample Program

Solve the following system of equations:


0.20Xl + 0.32X2 + 0.12X3 + 0.30X4 = 2.40
O.IOxl + 0.15X2 + 0.24x3 + 0.32x 4 = 2.40
0.20Xl + 0.24x2 + 0.46X3 + 0.36X4 = 3.50
0.60Xl + 0.40X2 + 0.32X3 + 0.20X4 = 3.16

1000 REM SAMPLE PROGRAM: PSOLUTN


1010 REM
1020 REM SOLVES A SYSTEM OF EQUATIONS A*X = B
1030 REM REQUIRES SUBROUTINES MATRED, MATWRT,
1040 REM SOLUTN, MATDET
1050 REM
1060 REM ARRAY DIMENSIONS:
1070 DIM A(4,5)
1080 DIM W(5)
1090 DATA 5, 4, "A", 5, 4, "A"
The Subroutines 153

1100 DATA 0.20, 0.32, 0.12, 0.30, 2.40


1110 DATA 0.10, 0.15, 0.24, 0.32, 2.40
1120 DATA 0.20, 0.24, 0.46, 0.36, 3.50
1130 DATA 0.60, 0.40, 0.32, 0.20, 3.16
1140 REM
1150 REM READ AND PRINT INPUT DATA
1160 REM CALL SUBROUTINE MATRED
1170 READ ACOL, AROW, RED$, MCOL, ODR, WRT$
1180 GOSUB 7000
1190 PRINT " INPUT MATRIX A:"
1200 GOSUB 8000
1210 REM EVALUATE AND PRINT RESULTS
1220 REM CALL SUBROUTINE SOLUTN
1230 LET ACOL = MCOL - ODR
1240 GOSUB 2000
1250 PRINT " SOLUTION MATRIX"
1260 GOSUB 8000
1270 END

>RUN
INPUT MATRIX A:

0.2 0.32 0.12 0.3 2.4


0.1 0.15 0.24 0.32 2.4
0.2 0.24 0.46 0.36 3.5
0.6 0.4 0.32 0.2 3.16

SOLUTION MATRIX

1
2
3
4

Hence from the computer printout, Xl =1, X2 =2, X3 =3 and X4 =4. This is an
exact solution and generally this method gives an exact solution if there are no
round-off and other errors. Most personal computers are accurate to eight or nine
significant figures.

Notes

1. If matrix A is singular, then the system of equations has an indeterminate


number of solutions. This situation is detected by the subroutine and the main
program is terminated with an appropriate message.
2. If the matrix A is found to be ill-conditioned, then the subroutine sends a
warning message but carries on to complete the computation without terminating
the main program. However the results obtained under this condition will be
unreliable.
3. Conte (1965), Bajpai et al. (1974) and Mason (1984) are suggested for further
reading.
154 Advanced BASIC Scientific Subroutines

SOLUTION OF A QUADRATIC EQUATION

Subroutine: QADEQN

Description

Finds the roots of a quadratic equation by an analytical method.

Method

The roots of a quadratic equation of the form Ax2 +Bx + C = 0 are given by the
formulae
Xl = -BI2A + y(D)I2A and X2 = -BI2A - Y(D)I2A
where D is the discriminant B2 -4A C. However. in the presence of significant
error the use of above formula may adversely affect the results. When AC is small
compared with B2 then better results can be obtained by making use of root-
product relation, that is
X2 == C/(A. X1)

The root Xl is calculated using the standard formula but in order to avoid the
terms (-B ± Y(D) )/2A becoming zero the sign of yD is chosen to be + if B is
negative and - if B is positive.
The types of roots are determined by the nature of the discriminant, that is
(i) if B2 - 4AC> 0 then Xl and X2 are real roots,
(il) if B2 - 4AC= 0 then Xl =X2,
(iii) if B2 - 4AC < 0 then Xl and X2 are complex roots.
These roots are stored in the output array R( ). Thus
Xl =R(l) + iR(2) and
X2 = R(3) + iR(4)
If the two roots are real then the imaginary parts R(2) and R( 4) are made zero.

Subroutine Listing

2000 REM QUADRATIC EQUATION


2010 REM
2020 REM SUBROUTINE: QADEQN
2030 REM
2040 REM EVALUATES ROOTS OF A QUADRATIC EQUATION
2050 REM
2060 REM VARIABLES:
2070 REM INPUT:
2080 REM A••..... COEFFICIENT OF r2
2090 REM B •.•.... COEFFICIENT OF X
The Subroutines 155

2100 REM C .....•. CONSTANT


2110 REM OUTPUT:
2120 REM R(l) .... REAL PART OF FIRST ROOT
2130 REM R(2) .... IMAGINARY PART OF FIRST ROOT
2140 REM R(3) .... REAL PART OF SECOND ROOT
2150 REM R(4) .... IMAGINARY PART OF SECOND ROOT
2160 REM LOCAL: ... DSCRMNT, VI, V2
2170 REM ARRAY DIMENSIONS:
2180 REM R() ••••• (4)
2190 REM
2200 REM CHECK FOR SMALL A
2210 IF ABS(A) <= 1E-30 THEN GO TO 2480
2220 REM
2230 REM EVALUATE DISCRIMINANT
2240 LET DSCRMNT ="B*B - 4*A*C
2250 LET VI = B/(2*A)
2260 LET V2 = SQR(ABS(DSCRMNT»/(2*A)
2270 IF DSCRMNT < 0 THEN GOTO 2400
2280 REM
2290 REM COMPUTE REAL ROOTS
2300 IF B < 0 THEN GOTO 2330
2310 LET R(l) = -VI - V2
2320 GO TO 2350
2330 REM
2340 LET R(l) = - VI + V2
2350 REM
2360 LET R(3) = C/ (A*R(1) )
2370 LET R(2) = o
2380 LET R(4) = o
2390 GOTO 2460
2400 REM
2410 REM SET VALUES IF COMPLEX ROOTS
2420 LET R(l) VI
2430 LET R(2) V2
2440 LET R(3) VI
2450 LET R(4) = -V2
2460 REM
2470 RETURN
2480 REM
2490 PRINT" SMALL VALUE OF A,"
2500 PRINT " LINEAR SOLUTION MAY BE APPROPRIATE"
2510 END

Sample Program

Find the roots of quadratic equation lOx 2 + 7x - 12 =O.

1000 REM SAMPLE PROGRAM: PQADEQN


1010 REM
1020 REM DETERMINES THE ROOTS OF A QUADRATIC EQUATION
1030 REM
1040 REM ARRAY DIMENSIONS
1050 DIM R(4)
156 Advanced BASIC Scientific Subroutines

1060 REM
1070 REM SET INITIAL VALUES
1080 LET A 10
1090 LET B 7
1100 LET C -12
1110 REM
1120 REM COMPUTE ROO'rS AND PRINT RESULTS
1130 REM CALL SUBROUTINE QADEQN
1140 GOSUB 2000
1150 PRINT " REAL PARTS IMAGINARY PARTS"
1160 PRINT
1170 PRINT R (1), R(2)
1180 PRINT
1190 PRINT R( 3), R(4)
1200 END

>RUN
REAL PARTS IMAGINARY PARTS

-1. 5 o
0.8 o

The two roots are -1.5 and 0.8.

Note

The value of coefficient A is checked for magnitude as small values may cause
overflow when the reciprocal is calculated. B2 and A. C are also computed by the
subroutine and place an upper limit on the magnitudes of A, Band C.
The Subroutines 157

SOLUTION OF A CUBIC EQUATION

Subroutine: CUBEQN

Description

Evaluates all roots of a cubic equation by the analytical method.

Method

The general form of a cubic equation


A1X3 +Azxz +A3X+A4 =0
can be transformed into its reduced form
y3 +Py+Q=O
by the substitution x = y - z/3 where z = Az/A 1 and
P= (3A3/Al -zZ)/3 and
Q = (2z 3 - 9zA3/Al + 27A 4/A 1)/27
Let a = (Q2/4 + p3 /27)t
b = -Q/2,~
c = (b + a)3 and
d= (b - a)t
then if a2 > 0, the roots of the reduced cubic equation are
Yl =c +d
Yz = -(c + d)/2 + i(c - dh/(3)/2
Y3 =(c + d)/2 - i(c - d)y(3)/2
If a 2 < 0 then y3 + Py + Q =0 can be solved using a trigonometric identity. Putting
y = Vcos 8, we have
V 3 cos3 8 + PVcos 8 = -Q (1)
Comparing with the trigonometric identity:
4cos3 8 - 3cos 8 = cos 38 (2)
If (1) = (2), then we have
V =± 2y(P/3) and cos 38 =3Q/PV
and hence
8 =1/3 (arc cos(Qy(27)/~)
Then the roots are
158 Advanced BASIC Scientific Subroutines

Yl =VCOS(J
Y2 = VCOS((J + 21f/3) and
Y3 = Vcos((J + 41f/3)
Finally, the roots of the original cubic equation are given by
Xl = Yl - z/3
X2 = Y2 - z/3 and
X3 = Y3 - z/3
The input array A() stores the coefficients of descending powers of X, while
the output array R( ) stores the roots of the cubic equation. Thus
Xl = R(I) + iR(2)
X2 = R(3) + iR(4) and
X3 = R(5) + iR(6)
If all the roots are real, then the imaginary parts of the roots iR(2), iRe 4) and
iR(6) are zero.

Subroutine Listing

2000 REM CUBIC EQUATION


2010 REM
2020 REM SUBROUTINE: CUBEQN
2030 REM
2040 REM FINDS ROOTS OF A CUBIC EQUATION
2050 REM BY AN ANALYTICAL METHOD
2060 REM
2070 REM VARIABLES:
2080 REM INPUT:
2090 REM A() ..... COEFFICIENT ARRAY WITH DESCENDING
2100 REM POWER OF X
2110 REM OUTPUT:
2120 REM R() ..... RESULT ARRAY, R(l), R(3) AND R(5)
2130 REM ARE REAL PARTS AND R(2), R(4) AND
2140 REM R(6) IMAGINARY
2150 REM LOCAL: ... THETA, P, Q, RPI, TLRNC, U1
2160 REM VI, V2, V3, VA, VB, VP, VQ, vz
2170 REM ARRAY DIMENSIONS:
2180 REM A() ..... (4)
2190 REM R() ..... (6)
2200 REM
2210 REM SET INITIAL VALUES AND CHECK FOR SMALL A
2220 LET RPI = 3.1415926536
2230 LET TLRNC = 1E-30
2240 IF ABS(A(l» < TLRNC THEN GOTO 2810
2250 REM
2260 REM TRANSFORM EQUATION
2270 LET VZ = A(2)/A(1)
The Subroutines 159

2280 LET VP A(3)/A(1) - VZ*VZ/3


2290 LET VQ 2*VZ*VZ*VZ/27 - VZ*A(3)/(3*A(1»
2300 LET VQ VQ + A(4)/A(1)
2310 LET VA VQ*VQ/4 + VP*VP*VP/27
2320 IF VA < 0 THEN GOTO 2540
2330 LET VA = SQR(VA)
2340 LET VB = -VQ/2
2350 REM
2360 REM COMPUTE ROOTS
2370 FOR P = 1 TO 2
2380 IF P = 1 THEN LET R(P) = VB + VA
2390 IF P = 2 THEN LET R(P) = VB - VA
2400 LET U1 = 0
2410 IF R(P) < 0 THEN LET Ul = 1
2420 IF ABS(R(P» < TLRNC THEN GOTO 2450
2430 LET R(P) = ABS(R(P»A(1/3)
2440 IF Ul = 1 THEN LET R(P) = -R(P)
2450 REM
2460 NEXT P
2470 LET R(4) (R ( 1) - R ( 2) ) * SQR ( 0 .75 )
2480 LET R(l) R(l) + R(2)
2490 LET R(2) o
2500 LET R(3) -R( 1)/2
2510 LET R(5) R(3)
2520 LET R(6) -R(4)
2530 GOTO 2730
2540 REM
2550 REM TRIG SOLUTION
2560 LET VI = ABS(VP)
2570 LET V2 = -(VQ/2)/SQR(Vl*Vl*Vl/27)
2580 IF ABS(V2) > TLRNC THEN GOTO 2610
2590 LET THETA RPI/2
2600 GOTO 2640
2610 REM
2620 LET THETA = ATN(SQR(1-V2*V2)/V2)
2630 IF V2 < 0 THEN LET THETA = THETA + RPI
2640 REM
2650 LET THETA = THETA/3
2660 LET V3 = 2*SQR(VI/3)
2670 LET R(l) V3*COS(THETA)
2680 LET R(3) V3*COS(THETA + (RPI/l.5»
2690 LET R(5) V3*COS(THETA + (2*RPI/1.5»
2700 LET R(2) 0
2710 LET R(4) 0
2720 LET R(6) 0
2730 REM
2740 REM DETERMINE ROOTS OF ORIGINAL EQUATION
2750 LET VZ = VZ/3
2760 LET R(l) R(l) - VZ
2770 LET R(3) R(3) - VZ
2780 LET R(S) R(5) - VZ
2790 REM
2800 RETURN
160 Advanced BASIC Scientific Subroutines

2810 REM
2820 PRINT" THE COEFF. OF X 3 IS SMALL. SOLUTION"
A

2830 PRINT " AS A QUADRATIC MAY BE APPROPRIATE "


2840 END

Somple Program

Solve x 3 + 3x2 + 6x - 3 = O.

1000 REM SAMPLE PROGRAM: PCUBEQN


1010 REM
1020 REM FINDS ALL ROOTS OF A CUBIC EQUATION
1030 REM
1040 REM ARRAY DIMENSIONS:
1050 DIM A( 4)
1060 DIM R(6)
1070 REM
1080 REM SET INITIAL VALUES
1090 LET A(l) = 1
1100 LET A(2) = 3
1110 LET A(3) = 6
1120 LET A( 4) = -3
1130 REM
1140 REM COMPUTE ROOTS
1150 REM CALL SUBROUTINE CUBEQN
1160 GOSUB 2000
1170 PRINT
1180 PRINT " REAL PARTS IMAGINARY PARTS"
1190 PRINT
1200 PRINT R( 1), R(2)
1210 PRINT
1220 PRINT R( 3), R(4)
1230 PRINT
1240 PRINT R (5) , R(6)
1250 END

>RUN
REAL PARTS IMAGINARY PARTS

0.40628758 0
-1.7031438 2.1173648

-1.7031438 -2.1173648

The roots of the cubic equation are 0.40628758, -1.7031438 + 2.1173648i


and -1.7031438 - 2.1173648i. The two complex roots appear as complex
conjugates.
The Subroutines 161

Notes

1. The variable TLRNC may be adjusted to suit the numerical range of the machine
in use.
2. Inverse cosine is not available on some versions of BASIC, though inverse
tangent generally is. ATN is employed to generate ACS when a trigonometrical
solution is required.
3. Stephenson (1969) and Lee and Lee (1982) are suggested for further reading.
162 Advanced BASIC Scientific Subroutines

NUMERICAL SOLUTION OF EQUATIONS

Subroutines: NEWITR and BISECT

Description

Finds the solution of an equation of the form I(x) = 0 by Newton's method and
the method of bisection.

Method

1. Newton's method. If Xj is an approximation to a root which satisfiesf(x) = 0,


then
j = 0,1,2 ...
yields successively closer approximations to the root where {'(Xj) is the value of
the derivative of f(x) at x = xI. This is Newton's formula for improving an
approximation of a root of f(x) = O. Newton's method will always converge if
the initial value, Xo , is chosen sufficiently close to the root.
It should be noted that the method fails if {,(x) is near to zero. The accuracy
of the method depends upon the precision to whichf(x)/{,(x) can be computed.
For example, if {,(x) is a non·zero, very small quantity, near the root then any
errors in I(x) will be enlarged when the ratio f(x)/{'(x) is computed. Under such
conditions it will be difficult to obtain good accuracy.
One disadvantage of Newton's method is that it has local convergence; that is,
the initial approximation to the root has to be close enough to the actual root
to ensure convergence. This presents a practical difficulty and some technique
for providing the initial estimate is desirable. The method of bisection can prove
useful here. The bisection method can be used to obtain a good approximation
to a root and then this may be improved upon by application of Newton's method.
2. Bisection method. This is a simple iterative technique for finding an approximate
root of a function. If a and b are two starting values of x and I(a) has sign opposite
to I(b) then, unless the function is discontinuous between these limits, a root lies
between a and b. By bisecting the interval and examining the sign of the function
at this point, a further subinterval is found in which there is a change in sign (unless
a root has been found). This process of bisection is repeated until the root is
determined with the required degree of precision. The value of the function will be
close to zero in the vicinity of the root and of large magnitude if a discontinuity
is encountered.
The Subroutines 163

Subroutine Listing

2000 REM NEWTON'S ITERATION METHOD


2010 REM
2020 REM SUBROUTINE: NEWITR
2030 REM
2040 REM FINDS A REAL ROOT OF AN EQUATION OF THE FORM
2050 REM F(X) = 0 BY NEWTON'S ITERATIVE METHOD
2060 REM
2070 REM VARIABLES:
2080 REM INPUT:
2090 REM D(X) ..•.. DERIVATIVE OF F(X). DEFINED IN
2100 REM MAIN PROGRAM BY DEF FN STATEMENT
2110 REM F(X) ..... EQUATION TO BE SOLVED. DEFINED IN
2120 REM MAIN PROGRAM BY DEF FN STATEMENT
2130 REM GRT ...... INITIAL GUESS VALUE OF A ROOT
2140 REM OUTPUT:
2150 REM RT ...... APPROXIMATE VALUE OF ROOT
2160 REM LOCAL: ..• CORR, 01, NUMITR, P, TLRNC, V1, Y1
2170 REM
2180 REM SET TOLERANCE, NUMBER OF INTERATIONS AND
2190 REM INITIAL VALUE OF ROOT
2200 LET TLRNC = 1E-6
2210 LET NUMITR = 50
2220 LET RT = GRT
2230 REM
2240 REM PERFORM ITERATIVE COMPUTATION
2250 FOR P = 1 TO NUMITR
2260 LET Y1 = FNF(RT)
2270 LET 01 = FND(RT)
2280 IF ABS(Dl) < 1E-30 THEN GOTO 2400
2290 LET CORR = Y1/D1
2300 LET RT = RT - CORR
2310 LET V1 = ABS(TLRNC*RT) + TLRNC
2320 IF ABS(CORR) < V1 THEN GOTO 2350
2330 NEXT P
2340 GOTO 2370
2350 REM
2360 RETURN
2370 REM
2380 PRINT " ROOT NOT FOUND"
2390 END
2400 REM
2410 PRINT" F' (X) NEAR ZERO,"
2420 PRINT" NEWTON'S METHOD UNSUITABLE"
2430 END
3000 REM THE BISECTION METHOD
3010 REM
3020 REM SUBROUTINE: BISECT
3030 REM
3040 REM FINDS A ROOT OF AN EQUATION OF THE
3050 REM FORM F(X) = 0 BY THE METHOD OF BISECTION
3060 REM
3070 REM VARIABLES:
164 Advanced BASIC Scientific Subroutines

3080 REM INPUT:


3090 REM F(X) .••• EQUATION TO BE SOLVED. DEFINED IN
3100 REM MAIN PROGRAM BY DEF FN STATEMENT
3110 REM X1,X2 ••• INTERVAL IN WHICH THE ROOT EXISTS
3120 REM OUTPUT:
3130 REM RT •.•.•• APPROX. ROOT WITHIN GIVEN BOUND
3140 REM LOCAL: ... V1, Y1, Y2, Y3, Zl, Z2
3150 REM
3160 REM CHECK FOR SIGN CHANGE IN FUNCTION
3170 REM AND SET TOLERANCE
3180 LET Zl = Xl
3190 LET Z2 = X2
3200 LET Y1 = FNF(Zl)
3210 LET Y2 = FNF(Z2)
3220 IF Y1*Y2 >= 0 THEN GOTO 3340
3230 LET TLRNC = 1E-6
3240 REM
3250 REM FIND ROOT TO REQUIRED TOLERANCE
3260 LET RT = (Zl + Z2)/2
3270 LET VI = ABS(TLRNC*RT) + TLRNC
3280 IF ABS(Z2 - Zl) < VI THEN GOTO 3320
3290 LET Y3 = FNF(RT)
3300 IF Y1*Y3 < 0 THEN LET Z2 = RT ELSE LET Zl RT
3310 GOTO 3250
3320 REM
3330 RETURN
3340 REM
3350 PRINT " NO SIGN CHANGE DETECTED BETWEEN BOUNDS"
3360 END

Sample Program

Find two real roots of the equation 4X4 - 2.5x 2 - X + 0.5 =0 by using first the
bisection method and then Newton's approximation. Use (0, 0.5) and (0.5, 1) as
the initial bounds and 0.25 and 0.75 as the starting value for the roots.

1000 REM SAMPLE PROGRAM: PNEWITR


1010 REM
1020 REM SOLVES AN EQUATION BY NUMERICAL METHODS.
1030 REM REQUIRES SUBROUTINES BISECT AND NEWITR
1040 REM
1050 REM DEFINE FUNCTIONS
1060 DEF FNF(X) = 4*X~4 - 2.5*X*X - X + 0.5
1070 DEF FND(X) = 16*X*X*X - 5*X - 1
1080 REM
1090 REM FIND ROOT BY BISECTION METHOD,
1100 REM DEFINE BOUNDS. CALL SUBROUTINE BISECT
1110 INPUT " LOWER BOUND "; Xl
1120 PRINT " LOWER BOUND = "; Xl
1130 INPUT " UPPER BOUND "; X2
1140 PRINT " UPPER BOUND = II-, X2
1150 GOSUB 3000
The Subroutines 165

1160 PRINT " ROOT BY BISECTION METHOD , RT


II.

1170 PRINT
1180 REM
1190 REM FIND ROOT BY NEWTON'S METHOD, INPUT INITIAL
1200 REM ROOT. CALL SUBROUTINE NEWITR
1210 INPUT " GUESSED ROOT "i GRT
1220 PRINT " GUESSED ROOT = " , GRT .
1230 GOSUB 2000
1240 PRINT " ROOT BY NEWTON'S METHOD " , RT .
1250 PRINT
1260 END

>RUN
LOWER BOUND 70
LOWER BOUND = 0
UPPER BOUND 1.5
UPPER BOUND = 0.5
ROOT BY BISECTION METHOD 0.303576

GUESSED ROOT 7.25


GUESSED ROOT = 0.25
ROOT BY NEWTON'S METHOD 0.3035763

>RUN
LOWER BOUND 1.5
LOWER BOUND = 0.5
UPPER BOUND 11
UPPER BOUND = 1
ROOT BY BISECTION METHOD 0.864243

GUESSED ROOT 1.75


GUESSED ROOT = 0.75
ROOT BY NEWTON'S METHOD 0.8642428

The required roots are 0.303576 and 0.864243. The accuracy of these solutions
may be checked by substituting back in the original equation.

Notes

1. For subroutine NEWITR the number of iterative cycles is limited to 50


(variable NUMITR); experience has shown this to be more than sufficient.
Imposing a limit on the number of iterations serves to stop the program should
it oscillate or should no root be found. The program will also fail to provide
usable output if the derivative computes to near zero. The subroutine issues a
warning in both cases and execution is interrupted.
2. The tolerance (variable TLRNC in both subroutines) is set to IE - 6; this can
be reduced for machines operating with high precision.
166 Advanced BASIC Scientific Subroutines

3. BISECT is simple to use and can prove helpful in indicating the location of roots.
Its disadvantage is that it converges more slowly than Newton's method and gener-
ally a greater time is required to achieve the desired accuracy.
4. Conte and De Boor (1972), Lee and Lee (1982), Miller (1981) and Mason
(1983) are suggested for further reading.
The Subroutines 167

2.11 Complex Numbers

COMPLEX NUMBER OPERATIONS

Subroutine: COMPLX

Description

Performs addition, subtraction, multiplication and division of two complex


numbers. Determines the reciprocal and square of a complex number and com-
putes polar and non-polar forms. Facilities for exchanging and copying two
complex numbers are also included.

Method

If x = a + ib and y = e + id then for:


(a) Addition
x + y = (a + e) + i(b + d)
(b) Subtraction
x - y = (a - e) + i(b - d)
( c) Multiplication
xy = (ae - bd) + i(ad + be)
(d) Division
x/y = [(ac + be) + i(be - ad)] j(e 2 + d 2 )
(e) Reciprocal
Ijx = (a - ib)j(a2 + b 2 )
(f) Square
x 2 = (a 2 _ b 2 ) + 2iab
(g) Polar form
Modulus = I x 1= v(a 2 + b 2 )
Argument, (J, in radians = arctan(b/a), -1r < (J .;;;; 1r. The quadrant is determined
by examination of the polarity of a and b as indicated below.

a b quadrant
+ve +ve 1st
+ve -ve 4th
168 Advanced BASIC Scientific Subroutines

-ve +ve 2nd


-ve -ve 3rd
(h) Inverse polar form
a =x cos(8)
b =x sin(8)
(i) Copy and exchange
Copy and exchange the contents of the memory locations of the real and imaginary
parts of complex numbers.

In the subroutine the operations are performed on two complex numbers,


AR + AI + BR and BI where R and I indicate the real and imaginary parts of
the number respectively. The results of addition, subtraction, multiplication and
division of the two complex numbers are stored in AR and AI, thus facilitating
further operations. Other operations (with the exception of copying and exchanges)
are performed on AR + AI alone. The required operation is selected by GOSUB to
the appropriate line number.

Subroutine Listing

2000 REM COMPLEX NUMBERS


2010 REM
2020 REM SUBROUTINE: COMPLX
2030 REM
2040 REM PERFORMS THE FOLLOWING OPERATIONS ON TWO
2050 REM COMPLEX NUMBERS: A = A + B, A = A - B,
2060 REM A = A*B, A = AlB, A = I/A, A =·A*A, A = B,
2070 REM AND B = A. ALSO EXCHANGES A AND B AND FINDS
2080 REM POLAR AND INVERSE POLAR FORMS
2090 REM
2100 REM VARIABLES:
2110 REM INPUT AND OUTPUT:
2120 REM AARG .... ARGUMENT OF A, RADIANS
2130 REM AI ...... IMAGINARy PART OF A
2140 REM AMOD .... MODULUS OF A
2150 REM AR ...... REAL PART OF A
2160 REM BI ...... IMAGINARy PART OF B
2170 REM BR ...•.. REAL PART OF B
2180 REM LOCAL: ... VI, V2
2190 REM
2200 REM ADDITION A = A + B
2210 REM
2220 LET AR = AR + BR
2230 LET AI = AI + BI
2240 GOTO 3090
2250 REM
2260 REM SUBTRACTION A A - B
2270 REM
2280 LET AR = AR - BR
The Subroutines 169

2290 LET AI = AI - BI
2300 GOTO 3090
2310 REM
2320 REM MULTIPLICATION A = A*B
2330 REM
2340 LET V1 = AR
2350 LET AR = AR*BR - AI*BI
2360 LET AI = V1*BI + AI*BR
2370 GOTO 3090
2380 REM
2390 REM DIVISION A = A/B
2400 REM
2410 LET V1 = AR
2420 LET V2 = BR*BR + BI*BI
2430 IF V2 = 0 THEN GOTO 3110
2440 LET AR = (AR*BR + AI*BI)/V2
2450 LET AI = (AI*BR - V1*BI)/V2
2460 GOTO 3090
2470 REM
2480 REM RECIPROCAL A = l/A
2490 REM
2500 LET V2 = AR*AR + AI*AI
2510 IF V2 = 0 THEN GOTO 3140
2520 LET AR = AR/V2
2530 LET AI = -AI/V2
2540 GOTO 3090
2550 REM
2560 REM SQUARE A = A*A
2570 REM
2580 LET V1 = AR
2590 LET AR = AR*AR - AI*AI
2600 LET AI = 2*V1*AI
2610 GOTO 3090
2620 REM
2630 REM POLAR FORM OF A
2640 REM
2650 LET RPI = 3.1415926536
2660 LET AMOD = SQR(AR*AR + AI*AI)
2670 IF AR = 0 THEN GOTO 2740
2680 LET AARG = ATN(AI/AR)
2690 REM
2700 REM DETERMINE QUADRANT FOR AARG
2710 IF AR < 0 AND AI < 0 THEN LET AARG AARG - RPI
2720 IF AR < 0 AND AI >= 0 THEN LET AARG = AARG + RPI
2730 GOTO 3090
2740 REM AR = 0
2750 IF AI = 0 THEN GOTO 3170
2760 IF AI < 0 THEN LET AARG = -RPI/2
2770 IF AI > 0 THEN LET AARG = RPI/2
2780 GOTO 3090
2790 REM
2800 REM INVERSE POLAR FORM OF A
2810 REM
2820 LET RPI = 3.1415926536
170 Advanced BASIC Scientific Subroutines

2830 IF AARG < -RPI OR AARG > RPI THEN GOTO 3210
2840 IF AMOD < 0 THEN GOTO 3210
2850 LET AR = AMOD*COS(AARG)
2860 LET AI = AMOD*SIN(AARG)
2870 GOTO 3090
2880 REM
2890 REM COpy B INTO A, A =B
2900 REM
2910 LET AR = BR
2920 LET AI = BI
2930 GOTO 3090
2940 REM
2950 REM COPY A INTO B, B A
2960 REM
2970 LET BR = AR
2980 LET BI = AI
2990 GOTO 3090
3000 REM
3010 REM EXCHANGE A AND B, A = B, B = A
3020 REM
3030 LET V1 = AR
3040 LET AR = BR
3050 LET BR V1
3060 LET V1 AI
3070 LET AI BI
3080 LET BI = V1
3090 REM
3100 RETURN
3110 REM
3120 PRINT" MODULUS OF B = 0 AT DIVISION"
3130 END
3140 REM
3150 PRINT" MODULUS A = 0 AT RECIPROCAL"
3160 END
3170 REM
3180 PRINT" AI = 0, AR = 0, AARG INDETERMINATE"
3190 PRINT" AT POLAR FORM"
3200 END
3210 REM
3220 PRINT" AMOD NEGATIVE OR AARG OUT OF RANGE AT ";
3230 PRINT "INVERSE POLAR"
3240 PRINT" AMOD = "; AMOD; " AARG = "; AARG
3250 END

Somple Program 1

Ifa = -2 + 3; andb = 1 + 2i, fmd the values ofa + b,a - b,ab and a/b.

1000 REM SAMPLE PROGRAM: PCOMPLX1


1010 REM
1020 REM COMPLEX NUMBER OPERATION
1030 REM
The Subroutines 171

1040 REM INPUT DATA


1050 DATA -2, 3, 1, 2
1060 REM
1070 REM PERFORM ADDITION
1080 READ AR, AI, BR, BI
1090 GOSUB 2200
1100 PRINT " REAL PARTS IMAGINARY PARTS"
1110 PRINT
1120 PRINT" A + B = ", AR, AI
1130 REM
1140 REM PERFORM SUBTRACTION
1150 RESTORE
1160 READ AR, AI
1170 GOSUB 2260
1180 PRINT
1190 PRINT" A - B = ", AR, AI
1200 REM
1210 REM PERFORM MULTIPLICATION
1220 RESTORE
1230 READ AR, AI
1240 GOSUB 2320
1250 PRINT
1260 PRINT" A :I< B = ", AR, AI
1270 REM
1280 REM PERFORM DIVISION
1290 RESTORE
1300 READ AR, AI
1310 GOSUB 2390
1320 PRINT
1330 PRINT " A / B " AR, AI
1340 END

>RUN
REAL PARTS IMAGINARY PAR'fS

A + B -1 5

A - B -3 1

A :I< B -8 -1

A / B 0.8 1.4

Hence
a + b = -1 + 5i
a-b=-3+Ii
ab = -8-Ii
alb = 0.8 + l.4i
These results are readily verified by direct calculation.
172 Advanced BASIC Scientific Subroutines

Sample Program 1

The input impedance of a circuit consisting of a series-parallel arrangement of


passive electrical components is given by

~n=zl+lKl~2+1~3+1~J
Determine the input impedance and input admittance (l/ziJ in complex and
polar form whenzl = 2 + 3j, Z2 = 5 + Ij, Z3 = 0 + 2j, Z4 = 3 - 4j.

1000 REM SAMPLE PROGRAM: PCOMPLX2


1000 REM
1020 REM COMPLEX NUMBER OPERATION
1030 REM
104(' REM DATA FOR Z2, Z3, Z4, Zl RESPECTIVELY
1050 DATA 5 , 1 , 0 , 2 , 3 , -4, 2, 3
1060 REM
1070 REM READ Z2, Z3, Z4 AND SUM THEIR RECIPROCALS
1080 READ AR, AI
1090 GOSUB 2480
1100 GOSUB 2950
1110 READ AR, AI
1120 GOSUB 2480
1130 GOSUB 2200
1140 GOSUB 2950
1150 READ AR, AI
1160 GOSUB 2480
1170 GOSUB 2200
1180 REM
1190 REM DETERMINE RECIPROCAL OF SUM AND ADD TO Zl
1200 GOSUB 2480
1210 READ BR, BI
1220 GOSUB 2200
1230 PRINT n CIRCUIT IMPEDANCE, REAL = "; AR;
1240 PRINT n, IMAGINARY = "; AI
1250 GOSUB 2630
1260 PRINT" POLAR FORM: MODULUS = ";AMOD;
1270 PRINT ", ARGUMENT = n; AARG; " RADIANS"
1280 PRINT
1290 GOSUB 2480
1300 PRINT n CIRCUIT ADMITTANCE, REAL= n; AR;
1310 PRINT ", IMAGINARY = "; AI
1320 GOSUB 2630
1330 PRINT" POLAR FORM: MODULUS n; AMOD;
1340 PRINT ", ARGUMENT = "; AARG; " RADIANS"
1350 END

>RUN
The Subroutines 173

CIRCUIT IMPEDANCE, REAL = 3.2971, IMAGINARY = 4.5719


POLAR FORM: MODULUS = 5.6368, ARGUMENT = 0.946 RADIANS

CIRCUIT ADMITTANCE, REAL= 0.10377, IMAGINARY = -0.14389


POLAR FORM: MODULUS = 0.17741, ARGUMENT = -0.946 RADIANS

Again the results displayed in the computer printout may be verified by direct
calculation.
References

Adams, A. G. (1969).'Areas under the normal curve', Algorithm 39, Computer J.,
12.
American National Standards Institute (1978). American National Standard for
Minimal BASIC, ANSI X3.60.
Angell, I. O. (1985). Advanced Graphics with the IBM Personal Computer,
Macmillan.
Angell, I. O. and Jones, B. J. (1983a). Advanced Graphics with the BBC Model B
Microcomputer, Macmillan.
Angell, I. O. and Jones, B. J. (1983b). Advanced Graphics with the Sinclair ZX
Spectrum, Macmillan.
Bajpai, A. C. et 01. (1974). Engineering Mathematics, Wiley.
Chatfield, C. (1970). Statistics for Technology, Penguin.
Conte, S. D. (1965) Elementary Numerical Analysis, McGraw-Hill.
Conte, S. D. and De Boor, C. (1972). Elementary Numerical Analysis - An
Algorithmic Approach, 2nd edition, McGraw-Hill.
Davis, O. L. and Goldsmith, P. L. (1972). Statistical Methods in Research and
Production, 4th edition, Oliver and Boyd.
Fox, L. and Mayers, D. F. (1968). Computing Methods for Scientists and
Engineers, Oxford University Press.
Froberg, C. E. (1970). Introduction to Numerical Analysis, 2nd edition, Addison-
Wesley.
Gosling, P. (1982). Practical BASIC programming, Macmillan.
Griffiths, P. and Hill, I. D. (editors) (1985a). 'Algorithm AS66 The normal integral'
by I. D. Hill, in Applied Statistics Algorithms, Ellis Horwood, p. 126.
Griffiths, P. and Hill, I. D. (editors) (1985b). 'Algorithm AS 147 A simple series for
the incomplete gamma integral', by Chi-Leung Lau, in Applied Statistics
Algorithms, Ellis Horwood, p. 203.
Griffiths, P. and Hill, I. D. (editors) (1985c). 'Algorithm AS63 The incomplete
beta integral', by K. L. Majumler and G. P. Bhattacharjee, in Applied Statistics
AlgOrithms, Ellis Horwood, p. 117.
Hamming, R. W. (1962). Numerical Methods for Scientists and Engineers, McGraw-
Hill.
Iyanaya, S. and Kawadu, Y. (editors) (1980). Encyclopedic Dictionary of Mathe-
matics, Mathematical Society of Japan, MIT Press.
Kreyszig, E. (1983). Advanced Engineering Mathematics, 5th edition, Wiley.
Lee, J. D. and Lee, T. D. (1982). Statistics and Computer Methods in BASIC,
Van Nostrand Reinhold.
Mason, J. C. (1983). BASIC Numerical Methods, Butterworths.
Mason, J. C. (1984). BASIC Matrix Methods, Butterworths.
Miller, A. R. (1981). BASIC Programs for Scientists and Engineers, Sybex.

174
References 175

Morgan, B. J. T. (1984). Elements of Simulation, Chapman and Hall.


Nevison, 1. M. (1978). The Little Book of BASIC Style, Addison-Wesley.
Pearson, K. (editor) (1956). Tables of the Incomplete Gamma Function, Cambridge
University Press.
Pearson, K. (editor) (1968). Tables of the Incomplete Beta Function, 2nd edition,
Cambridge University Press.
Ralston, A. and Wilf, H. S. (1962). Mathematical Methods for Digital Computers,
Wiley.
Scheffe, H. (1959). The Analysis of Variance, Wiley.
Stephenson, G. (1969). Mathematical Methods for Science Students, 6th edition,
Longmans Green.
Stroud, K. A. (1982). Engineering Mathematics, 2nd edition, Macmillan.
Wonnacott, T. H. and Wonnacott, R. J. (1981). Regression: A Second Course in
Statistics, Wiley.
Index

Accuracy see Error Density functions see Probability


ACS 161 Determinant 119-24
ALGOL language 2 Differential equations 138-44
Amstrad 4 DIM 5
Analysis of variance 72-87, 89 Discriminant 154
ANOV A see Analysis of variance Distribution functions see Probability
Array variables 5
ATN 4,161 Eigenvalues 114-18
Average see Mean Eigenvectors 114-18
ELSE 6
BASIC language 1-2 END 5
BBC micro 4 Enhancements
Bernoulli distribution see Binomial Equations
distribution cubic 157-61
Bernoulli numbers 31 quadratic 154-6
Beta function 37-41, 47 simultaneous linear 151-3
Binomial distribution 9-11,20-1 solutionof 151-66
Bisectional method 162-6 Error, standard see Standard error
Bugs 7 Errors, rounding, syntax, precision
6-7, see also Bugs
C computer language 2 Exponential distribution 18-19,29-30
Calculus 138-50 Exponential random numbers 12, 18-19
Chebyshev polynomial 128-32
Chi-squared 64-8 F distribution 45-7
distribution 42-4 F ratio, F test 46, 72, 74, 77-8,83,
Combinations 69-71 85,89
Complex numbers 167-73 Factorials 69-71
Complex roots 154,158 FN 6
Contingency table 64-8 FOR-NEXT 5
Control variables 5-6 FORTRAN language 2
Correlation 88 Fourier coefficients, series 133-8
Cubic equati0ns 157-61 Frequency data see Cumulative
Cumulative distribution functions frequencies
see Probability Functions 4-6
Cumulative frequencies 53-7
Curve fitting see Regression and Gamma function 31-6,42,45,47,69
Interpolation Gauss elimination 119
Gaussian distribution see Normal
Data, integration of discrete 145-50 distribution
DAT A statement 4 Global variables 5
DEF FN 6 GOSUB 3

176
Index 177

GOTO 2 Orthogonal matrix transformation 114


Graphics 4-5
Paired comparisons 58-63
Harmonic coefficients 133-7 Pascal language 2
Harmonic index 133-7 Percentiles 53-7
Hewlett-Packard 4 Permutations 69-71
Pivotal condensation 119
IBM 4 Poisson distribution 12, 22-4
Identity matrix 89 Polar form 167
IF-THEN, IF-THEN-ELSE, IF-THEN- Polynomial regression 100-3
GOTO 6 Polynomials see Chebyshev polynomial
Ill-conditioning 99, 124 Portability 4
Imaginary 154, 158 Presentation 2
Integer variables 5 PRINT 4
Integration, numerical 7, 145-50 Probability see also Random numbers
Interpolation 125-7 binomial 20-1
Inverse matrix 119-24 exponential 29-30
normal 25-8
Jacobi diagonalisation 114 Poisson 22-4
Procedures 1
Lagrange interpolation 125-7
Least squares estimation see Regression Quadratic equation 154-6
LET 6
Line numbers 3, 8 R2 103
LN 4,6-7 Random numbers 4, 8
Local variables 5 binomial 9-11
LOG 4 exponential 18-19
LPRINT 4 normal 15-17
Poisson 12-14
Matched samples see Paired comparisons uniform or rectangular 6,12,15,18
Matrix Range 53-7
addition, multiplication, read, Real roots 154,158
subtraction, transposition, Real symmetric matrix 114
write 104-13 Rectangular distribution see Uniform
determinant of 119-24 distribution
eigenvalues, eigenvectors, real Regression 87-103
symmetric 114-18 Regression coefficients 87, 89, 98-9
inversion 119-24 REM 2
Maximum value 53-7 Replicates 77, 83
Mean 50-2, 72, 88 Residual 76,85, 99
Means, difference between 58-63 Residual analysis 87, 90
Median 53-7 RETURN 2
Minimum value 53-7 RND 6
Multiple assignment statements 5 Rounding errors 6-7,99,103,119
Multiple linear regression 87-99 Runge-Kutta method 138-44
Multiple regression coefficient 89
Multiple statement lines 2, 5 Shell sort 53
Significant figures 4
N(O, 1) see Normal distribution Simpson's rule 7, 145-50
Newton's method 162-6 Simulation 7,10-11,13-14,16-19
Normal distribution 15-17 25-8 Simultaneous equations 7, see also
Normal equations 87,89, 99 Equations
Numerical integration 145-50 Software viii, 6
178 Index

Solution of equations 151-66 t distribution 47-9,58-63


Sorting 53-7 t test 58-63
Spectrum 4 THEN 6
Speed 1-3,8 Time 7, see also Speed
Standard deviation 50-2 Trapezium rule 145-50
Standard error 58-63, 87-90 Triangular matrix 119
Standardised residual 90
Statements 4-5
STEP 5 U(O, 1) see Uniform distribution
Stirling's approximation 31 Uniform distribution 6,12,15,18
STOP 5
String variables 5
Structure 2-3 Variables, array, control, global, local,
Student's t distribution 47-9,58-63 integer, string 4-5
Style 3 Variables, random see Random
Subroutine viii, ix, 1,3,8 numbers
Summary statistics 51 Variance 50-2, 58-63
Syntax 4 Variance ratio see F ratio
Software Diskette

A diskette containing all the programs included in


this book for use on an IBM PC is available
(ISBN 0-333-46912-7).

Details of prices and availability can be obtained from


Publisher for Computing Books
Macmillan Education
Houndmills
Basingstoke RG21 2XS

You might also like