LABTITLE=: 'Finite mathematics'
LABAUTHOR=: 'KEI'
LABERRORS=: 1

NB. =========================================================
Lab Chapter INTRODUCTION
NB. =========================================================
Lab Section A. Purpose and Notation

This lab is written as a companion to K. Stephen Brown, et al.,
Finite Mathematics, Holt, Rinehart and Winston of Canada,
ISBN 0-03-922023-0, 1988, designed for use in Grade 13 in Ontario
schools. It will be referred to here as FM.

The use of the computer makes it possible to experiment with
mathematical ideas with ease and precision, often providing new insights.

Experiments may also be used to clarify any new notation encountered. For
example, your understanding of the use of parentheses, and of notation
for addition, multiplication, and power may be tested as follows:
)
PREPARE

require 'plot graph'
PLOT=:'stick,line'&plot
hist=:'stick'&plot
surf=:'surface'&plot
color=:viewmat

E1=:<@(<:@]) C. [
E2=:[ * 1: + -@{:@] |. -@#@[ {. <:@{:@|.@]
E3=:1&{@]`(<@:<:@({.@] , 2&{@]))`(=@i.@#@[)} +/ .* [
mp=:+/ . *
box=:<"0
TO=:(-/@(?@((2: , [) $ >:@])))
TOR=:(-/@(?.@((2: , [) $ >:@])))
decimal=:x:^:_1
sort=:/:~
csub=:<:@] {"1 [ NB. Column subscript
rsub=:<:@] { [  NB. Row subscript
sub=:(<:@] { [)`(([ (<:@] { [) >@{.@]) (<:@] {"1 [) >@{:@])@.(<:@#@$@[ *. #@]>1:) NB. Subscript

each=:&.>
poly=:|.@[ p. ]

tnp0=:   0.5  0.504  0.508  0.512  0.516 0.5199 0.5239 0.5279 0.5319 0.5359
tnp1=:0.5398 0.5438 0.5478 0.5517 0.5557 0.5596 0.5636 0.5675 0.5714 0.5753
tnp2=:0.5793 0.5832 0.5871  0.591 0.5948 0.5987 0.6026 0.6064 0.6103 0.6141
tnp3=:0.6179 0.6217 0.6255 0.6293 0.6331 0.6368 0.6406 0.6443  0.648 0.6517
tnp4=:0.6554 0.6591 0.6628 0.6664   0.67 0.6736 0.6772 0.6808 0.6844 0.6879
tnp5=:0.6915  0.695 0.6985 0.7019 0.7054 0.7088 0.7123 0.7157  0.719 0.7224
tnp6=:0.7257 0.7291 0.7324 0.7357 0.7389 0.7422 0.7454 0.7486 0.7517 0.7549
tnp7=: 0.758 0.7611 0.7642 0.7673 0.7704 0.7734 0.7764 0.7794 0.7823 0.7852
tnp8=:0.7881  0.791 0.7939 0.7967 0.7995 0.8023 0.8051 0.8078 0.8106 0.8133
tnp9=:0.8159 0.8186 0.8212 0.8238 0.8264 0.8289 0.8315  0.834 0.8365 0.8389
tnp10=:0.8413 0.8438 0.8461 0.8485 0.8508 0.8531 0.8554 0.8577 0.8599 0.8621
tnp11=:0.8643 0.8665 0.8686 0.8708 0.8729 0.8749  0.877  0.879  0.881  0.883
tnp12=:0.8849 0.8869 0.8888 0.8907 0.8925 0.8944 0.8962  0.898 0.8997 0.9015
tnp13=:0.9032 0.9049 0.9066 0.9082 0.9099 0.9115 0.9131 0.9147 0.9162 0.9177
tnp14=:0.9192 0.9207 0.9222 0.9236 0.9251 0.9265 0.9279 0.9292 0.9306 0.9319
tnp15=:0.9332 0.9345 0.9357  0.937 0.9382 0.9394 0.9406 0.9418 0.9429 0.9441
tnp16=:0.9452 0.9463 0.9474 0.9484 0.9495 0.9505 0.9515 0.9525 0.9535 0.9545
tnp17=:0.9554 0.9564 0.9573 0.9582 0.9591 0.9599 0.9608 0.9616 0.9625 0.9633
tnp18=:0.9641 0.9649 0.9656 0.9664 0.9671 0.9678 0.9686 0.9693 0.9699 0.9706
tnp19=:0.9713 0.9719 0.9726 0.9732 0.9738 0.9744  0.975 0.9756 0.9761 0.9767
tnp20=:0.9772 0.9778 0.9783 0.9788 0.9793 0.9798 0.9803 0.9808 0.9812 0.9817
tnp21=:0.9821 0.9826  0.983 0.9834 0.9838 0.9842 0.9846  0.985 0.9854 0.9857
tnp22=:0.9861 0.9864 0.9868 0.9871 0.9875 0.9878 0.9881 0.9884 0.9887  0.989
tnp23=:0.9893 0.9896 0.9898 0.9901 0.9904 0.9906 0.9909 0.9911 0.9913 0.9916
tnp24=:0.9918  0.992 0.9922 0.9925 0.9927 0.9929 0.9931 0.9932 0.9934 0.9936
tnp25=:0.9938  0.994 0.9941 0.9943 0.9945 0.9946 0.9948 0.9949 0.9951 0.9952
tnp26=:0.9953 0.9955 0.9956 0.9957 0.9959  0.996 0.9961 0.9962 0.9963 0.9964
tnp27=:0.9965 0.9966 0.9967 0.9968 0.9969  0.997 0.9971 0.9972 0.9973 0.9974
tnp28=:0.9974 0.9975 0.9976 0.9977 0.9977 0.9978 0.9979 0.9979  0.998 0.9981
tnp29=:0.9981 0.9982 0.9982 0.9983 0.9984 0.9984 0.9985 0.9985 0.9986 0.9986

TNP=:>tnp0;tnp1;tnp2;tnp3;tnp4;tnp5;tnp6;tnp7;tnp8;tnp9;tnp10;tnp11;tnp12;tnp13;tnp14;tnp15;tnp16;tnp17;tnp18;tnp19;tnp20;tnp21;tnp22;tnp23;tnp24;tnp25;tnp26;tnp27;tnp28;tnp29

mt0=:22700 9279 5682 5479 5078 4578 3979 3778 3779 3180
mt1=:3179 2979 3177 3473 4762 7040 10206 12571 14136 14807
mt2=:14686 14468 14151 13935 13719 13406 12997 12492 12086 11876
mt3=:11862 11944 12027 12302 12674 13237 13894 14741 15873 17288
mt4=:18790 20476 22437 24575 27077 29936 33336 37076 41055 45168
mt5=:49407 54225 59967 66783 74355 82187 89891 97617 105073 112758
mt6=:121644 132378 145036 158918 173180 186713 199422 211289 222867 235029
mt7=:248003 261316 273930 284873 293568 299888 304616 309039 313236 316439
mt8=:317996 317653 315311 310794 302854 290854 274766 255081 232569 208248
mt9=:183137 158217 134450 112589 93057 75967 61194 48468 37470 27930
mt10=:19700 12789 7329 3470 1205 229

mtt=:mt0,mt1,mt2,mt3,mt4,mt5,mt6,mt7,mt8,mt9,mt10

mtf=:{&(1e_7*mtt) NB. Mortality function (page 437)

border=:1 : 0
u. border~y.
:
(' ';,.x.),.({.;}.)":y.,x. u./y.
)

PREPARE
3+2
3*2
3^2
(2+3)*4
2+(3*4)

NB. Anything following NB. is a comment, and is not executed.

NB. =========================================================
Lab Section

The following examples are commented:
)
(2+3)*4

(2+3)4      NB. The symbol for multiplication must not be omitted

4-2         NB. The symbol for subtraction
4%2         NB. The symbol for division
2-3         NB. _1 denotes negative 1 (_ is not the symbol for subtraction)
2%3         NB. Result is a decimal approximation
2%3x        NB. 3x is extended precision. Result is exact.
1r3+1r2     NB. Sum of fractions
1r3*1r2     NB. Product of fractions

NB. Use the up-arrow to scroll back.

NB. =========================================================
Lab Section

The symbols < = > are used as comparisons, but they give results, just as do other
functions such as + and *. The result is 0 if the relation
does not hold, and 1 if it does. The 0 and 1 may therefore be interpreted
as "false" and "true".

To assign a value to a name (as in "Let x=3"), we do not use =, but instead use the two-character
symbol =: (analogous to the copulas "is" and "are" in English). For example:
)
x=:3 NB. Read as "x is 3"

x<3

x=3

4>x

NB. =========================================================
Lab Section B. Systems of Linear Equations

The equation x + 4y = -1 on page 1 of FM may now be expressed on the
computer, first assigning values to x and y, and using parentheses
to make expressions unambiguous:
)
x                  NB. Enter x to recall the value assigned to it.

y=:1               NB. Assign a value to y

x + (4 * y)

(x + (4 * y)) = _1 NB. The equation is not true for these values

y=:_1

(x + (4 * y)) = _1 NB. But is for the new value of y

(x + (4 * y)) ; (_1) ; ((x + (4 * y)) = _1) NB. Show all together

NB. =========================================================
Lab Section

An equation remains true (or false) if its "limbs" (on either side of
the = sign) are modified in the same way. For example:
)
_1 - x                         NB. Subtract x from right limb

(x + (4 * y)) - x              NB. Subtract x from  left limb

((x + (4 * y)) - x) = (_1 - x) NB. Equation remains true

4*y          NB. New left limb (addition and subtraction of x cancel)

(4*y) % 4    NB. Divide left limb by 4

y            NB. To leave y

(_1 - x) % 4 NB. New right limb

y ; ((_1 - x) % 4) ; (y = ((_1 - x) % 4)) NB. Show both limbs and equation

NB. =========================================================
Lab Section

The final equation y = ((_1 - x) % 4) is equivalent to the initial
equation from FM. Since y alone appears on the left, we can think of
this as defining y as a function of x. We can make this explicit by
replacing = by the copula =: so that any given value of x assigns
an appropriate value to y.

Furthermore, to reflect the fact that this concerns Equation 1 of FM,
we will use the name y1 instead of y. Thus:
)
x=:5

y1 =: ((_1 - x) % 4)

y1

x=:0 1 2 3 4 5 6 7 8 9 NB. Assign a list of values to x

y1 =: ((_1 - x) % 4)   NB. Compute corresponding values of y

y1

NB. =========================================================
Lab Section

 We now have the values y1 resulting
 from applying the function defined
 by the equation of FM to the argument
 list x, and will use the function
 PLOT to plot them against the
 argument x:

 Before advancing to the next panel,
 press the Esc key to remove the plot
 window.

 Also use the up-arrow and down-arrow
 to scroll over earlier work:
)
PLOT x;>y1

NB. =========================================================
Lab Section

Observe the following plot of two functions together:
)
y2=:y1-2

y2


PLOT x;>y1;y2

NB. =========================================================
Lab Section

Assign values to y3 so that it is a solution
to Equation 2 on page 1 of FM, and plot the
three results y1 and y2 and y3 together. If you
do not wish to attempt this, simply continue to
the next panel to see exactly what to enter.

What do the intersections in the plot tell
of common solutions to the three functions?
)

NB. =========================================================
Lab Section

Enter the expressions:

   y3=:(9 - (2*x)) % _3

   PLOT x;>y1;y2;y3

and compare the results with your own.

You may enter them directly on the keyboard, or scroll back so
that the cursor rests on the first of them, press the Enter key
to bring it down to the input area, and again press Enter to execute
it. Then repeat for the second expression.

Note that an expression brought to the input area may be edited
(using the left and right arrows, the Delete key, and the main
keyboard to enter new material) before pressing Enter to
execute it
)

NB. =========================================================
Lab Section

What do you conclude from the resulting plot?

Read the coordinates of the point of intersection of the
lines (3 _1, that is, x is 3, and y is _1), and use these values
in the expressions for the two equations of FM, and affirm that
they satisfy both.
)

NB. =========================================================
Lab Section C. Matrix Notation

Matrices may be entered in various ways. We will use the first
matrix shown (in large brackets) in Section 1.2 of FM to illustrate
two of them: the use of comma-dot (,.) to stitch together columns, and the use
of comma (,) to catenate rows for a final application of the shape
function ($):
)
1 2 1,._2 _1 3,.2 _1 1

m1=:1 2 1,._2 _1 3,.2 _1 1 NB. Assign the name m1 to the matrix

r1=:1 _2 2
r2=:2 _1 _1
r3=:1 3 1

r1,r2,r3                   NB. Catenate to form a single list

3 3 $ r1,r2,r3             NB. Shape to a 3-by-3 matrix

m2=:3 3 $ r1,r2,r3         NB. Assign the name m2

m1;m2

NB. =========================================================
Lab Section

Stitching may also be used to add further columns needed
in an augmented matrix. For example, the matrix A on the
following page is obtained as follows:
)
m1,.1 _5 4

A=:m1,.1 _5 4

NB. =========================================================
Lab Section

The functions csub and rsub select columns and rows from matrices.
We will illustrate their use by selecting the matrix of coefficients
from the augmented matrix A, using it with the matrix product
(defined on page 82) and the list _1 1 2 (known to be the solution
of the augmented system) to obtain a result equal to the column of
constants of A:
)
A csub 1 2 3              NB. The matrix of coefficients

(A csub 1 2 3 ) mp _1 1 2 NB. Matrix product with solution

A csub 4                  NB. The vector of constants

NB. =========================================================
Lab Section D. Elementary Row Operations
The three elementary row operations listed in the box at
the bottom of page 9 of FM will be effected here by
the functions E1, E2, and E3. Their use will be illustrated on the augmented matrix
A of Example 2 (page 10).
)
A=:2 _1 _4,._2 0 _3,.1 2 _1,.4 _1 3
A

A E1 1 2   NB. Interchange rows 1 and 2

A E2 3 2   NB. Row 2 is 3 times row 2

A E3 3 2 1 NB. Row 3 is row 3 plus 2 times row 1

NB. =========================================================
Lab Section

Modified systems produced by elementary row operations possess the same
solution. For example:
)
sol=:(A csub 4) %. (A csub 1 2 3) NB. "matrix divide" gives solution

sol

(A csub 1 2 3) mp sol

A csub 4

B=:A E3 3 2 1

B

(B csub 1 2 3) mp sol

B csub 4

NB. =========================================================
Lab Section

The following shows the sequence of elementary operations
used to solve the system A of Section 1.3 of FM (page 13):
)
A=:1 4 3,._4 _1 _2,.3 _2 1,.2 _3 4
A

]A1=:A E3 2 _4 1 NB. The identity function ] displays A1

]A2=:A1 E3 3 _3 1

]A3=:(A2 E2 3 3) E3 3 _2 2 NB. Two steps combined, as in FM

NB. =========================================================
Lab Section

Use the elementary operations to produce the steps in
the solution of Example 2 (page 16), and for further
examples from Chapter 1.
)

NB. =========================================================
Lab Chapter LINEAR INEQUALITIES
NB. =========================================================
Lab Section 2.1 Graphing Linear Equations


 The lines of Example 5,
 Section 2.1 of FM are
 expressed as x - y = 2
 and 2x + y = 1. We re-
 express them as
 y = _2 + x and
 y = 1 - 2 * x, and
 plot them as shown below.

(Press the key Esc to remove the plot.)
)
x=:_3 _2 _1 0 1 2 3 4

y1=:_2 + x

y2=:1 - 2 * x

>y1;y2

PLOT x ; >y1;y2

NB. =========================================================
Lab Section

A line parallel to the second line may be added as shown
below. The lines needed to represent constraints may be
treated similarly; in particular, to provide the figures
needed in linear programming:
)
y3=:1 - 2 * x - 1
y3
PLOT x ; >y1;y2;y3

NB. =========================================================
Lab Section

The following shows a similar plot of three functions,
the first two of which (double and halve) are clearly
linear.

We might therefore say that we are plotting not linear
equations, but the linear functions defined by equations:
)
x=:i:3

x

PLOT x;>(+: x);(-: x);(*: x)

NB. =========================================================
Lab Section

But consider the the equation y=3, whose graph is a horizontal
line representing a constant value of 3 for y.

Considered as a function this is a CONSTANT function. What is
the proper notation for such a function? It cannot be 3,
because this is a number, not a function, and cannot be
applied to an argument x as in 3 x .

We use the notation 3"0, as illustrated below:
)
3"0 x

3 x NB. The number 3 is not a function.

PLOT x;>(+: x);(*: x);(3"0 x)

NB. =========================================================
Lab Chapter APPLICATIONS OF MATRICES
NB. =========================================================
Lab Section A. Introduction

The list of cities and the corresponding communication
matrix of Example 2 (page 68) can be entered as shown
below. Moreover, the
transpose function |: can be applied to it and the result
can be compared to it by using the match function -: to test
the assertion that it is symmetric.
)
]cities=:'Edmonton';'Winnipeg';'The Pas';'Flin Flon';'Lynn Lake';'Thompson'

]C=:0 1 0 0 0 0,.1 0 1 0 0 0,.0 1 0 1 0 1

]C=:C,.0 0 1 0 1 1,.0 0 0 1 0 1,.0 0 1 1 1 0

C -: |:C NB. C matches (-:) its transpose (|:)

NB. =========================================================
Lab Section

A more readable version of the table C can be made by
appending to it the boxed list of cities, after first
boxing the individual elements of C:
)
box C
cities,box C NB. A seven rowed table (More in next panel)

NB. =========================================================
Lab Section
)
' ';cities   NB. A 7-element "conformable" list

(' ';cities),.cities,box C

NB. =========================================================
Lab Section

The foregoing steps can be collected to define a function
(called frame) such that cities frame C produces the framed matrix.

Use the information from Exercise 3 a) (page 70) to define a list
of royalty (to be called Tudors) and a corresponding connection
matrix T. Then enter Tudors frame T to produce a frameed table.
)
frame =:(' '&;@[) ,. [ , box@]

cities frame C

NB. =========================================================
Lab Section B. Adding and Subtracting Matrices

The expression 3 4 TO 5 generates
a matrix of 3 rows and 4 columns with integer elements chosen at
random in the interval _5 to 5. We will use such random
matrices to illlustrate the application of addition, subtraction,
and other functions to matrices.
)
A34=:3 4 TO 5

B34=:3 4 TO 5

C43=:4 3 TO 5

A34;B34;C43

A34+B34

A34-B34

A34+C43

NB. =========================================================
Lab Section

Although the functions applied to matrices in FM are
limited to + and - and matrix product (denoted here by mp),
we will also use a variety of other functions. For example:
)
A34;B34;C43

A34 mp C43 NB. Matrix product -- result is 3 by 3

C43 mp A34 NB. Matrix product -- result is 4 by 4

A34<B34    NB. Less than comparison

A34<.B34   NB. Minimum (lesser-of)

NB. =========================================================
Lab Section

We continue with further examples:
)
A34;B34

|A34    NB. Magnitude

A34*B34 NB. NOT matrix product

A34^B34 NB. Power

A34%B34 NB. Division

A34%x:B34 NB. Fractions expressed as rationals.


NB. =========================================================
Lab Section

In some experiments it is convenient to use a "repeatable"
random generator. This is provided by TOR, as illustraed below:
)
4 4 TOR 10

4 4 TOR 10

NB. =========================================================
Lab Section

#2b and #2c and #3 of Exercises 3.3 of FM (page 85) use the
matrix product on two vectors, on a matrix and a vector,
and in the square of a matrix. Thus:
)
mp=:+/ . *        NB. Matrix product

_1 2 3 mp 4 _1 2  NB. These vectors are perpendicular

M=:> 1 _3 4 ; 1 2 1 ; _1 2 3

'x y z'=:4 _1 2

M;x;y;z

M mp x,y,z

M mp M             NB. "Square" of M

M mp M mp M        NB. Third power of M

NB. =========================================================
Lab Section C. Determinants and Eigenvalues

#5 of Problems 3.2 of FM (page 81) defines the determinant of a 3-by-3 matrix, and requires it to be applied to the matrix A-lambdaI to determine a value of the scalar lambda to yield a zero determinant (in which case lambda is said to be an eigenvalue of A). Thus:
)
A=:> 5 0 1 ; 6 8 0 ; 0 0 _2

I=:> 1 0 0 ; 0 1 0 ; 0 0 1

A ; I ; A - 9 * I

det=: -/ . *   NB. Determinant for any square matrix

det A - 9 * I
det A - 6 * I

det A - 8 * I  NB. 8 is an eigenvalue of A

det A - 5 * I  NB. 5 is an eigenvalue of A

det A - _2 * I NB. _2 is an eigenvalue of A

NB. =========================================================
Lab Section D. Linear Systems and Inverses

The expression %.m gives the inverse of a matrix m, and v%.m "divides"
the vector v by the matrix m, in the sense that m mp (v%.m) gives v. We will illustrate
this on the system of Example 1 of Section 3.4 (page 91):
)
Ex1=:1 1 0 1,.0 2 2 _2,._2 _3 3 1,.3 0 _4 _1,.6 1 5 0

Ex1 ; (%. Ex1 csub 1 2 3 4)

det Ex1 csub 1 2 3 4

sol=:(Ex1 csub 5)%.(Ex1 csub 1 2 3 4)

sol

(Ex1 csub 1 2 3 4) mp sol

Ex1 csub 5

NB. =========================================================
Lab Chapter TECHNIQUES FOR COUNTING
NB. =========================================================
Lab Section A. Tables

 If digits=:0 1 2 3 4 5 6 7 8 9,
 then digits +/ digits gives an
 addition table. The pattern  of
 such a table may be emphasized
 by assigning a distinct color to
 each distinct value in the table.

 To proceed, you must first press
 Esc to remove the color window.
)
digits=:0 1 2 3 4 5 6 7 8 9

digits +/ digits

color digits +/ digits

NB. =========================================================
Lab Section

The addition table of Example 3 (page 107) may be produced similarly,
and may be bordered by its arguments (for easy reading) by using "border" instead of "/":
)
tens=:10 20 30 40 50 60 70 80 90

tens +/ digits

tens +border digits

NB. =========================================================
Lab Section

Example 1 of Section 4.1 of FM shows a similar table of the catenation of two lists of words. We will use boxed lists of the words together with the function f=:,~each to
catenate (,) them in reverse order (,~) for each of the boxed elements.
We will then border the table by its arguments.

Unlike the table in FM, the elements of the table are capitalized
in agreement with the argument at the top of the bordered table.
)
size=:'Small ';'Medium ';'Large '
size
colours=:'black';'brown';'grey';'burgundy'
colours

f=:,~each
colours f/ size

NB. =========================================================
Lab Section

We now append the list of sizes as a row at the
top of the table, then extend the list of colours by
'Colour\Size', and use ,. to append it as a column:
)
size,colours f/ size

'Colour\Size' ; colours

('Colour\Size' ; colours) ,. size,colours f/ size

NB. =========================================================
Lab Section A. Introduction

Since integers may be used to index (select from) lists
of letters or boxed words, numeric tables may also be
used to produce non-numeric tables. For example:
)

ALPH=:'ABCDEFGH'

0 { ALPH NB. indices begin at 0 (called 0-origin)

1 { ALPH

2 0 6 4 { ALPH

(i.2 3) { ALPH

(i.2 3) { words=:'Now';'is';'the';'time';'for';'all';'good';'men'

2 3 1 0 { words

NB. =========================================================
Lab Section

Example 7 (page 108) of FM concerns the 2-digit positive
integers (p2d=:10+i.90). The remainders on dividing by 5
are given by 5 | p2d, those divisible by 5 are those that
have a zero remainder (identified by 0=5 | p2d), and they
may be counted by applying +/ (the "sum over" function):
)
p2d=:10+i.90

p2d

5|p2d

0=5|p2d

+/0=5|p2d

NB. =========================================================
Lab Section

To continue:
)
d2=:0=2|p2d   NB. Boolean list identifying #s divisible by 2

d5=:0=5|p2d

(+/d2),(+/d5) NB. The individual sums

(+/d2)+(+/d5) NB. Their total

d2 *. d5      NB. Those divisible by both 2 and 5 (*. is "and")

+/(d2*.d5)    NB. The number divisible by both 2 and 5

(45+18)-9     NB. Number divisible by either 2 or 5

NB. =========================================================
Lab Section B. Permutations of Distinct Objects

We will generate the table of Example 1 (page 112) by first
generating a table of all possible combinations, and then
suppressing those that are not distinct. Although possibly
"wasteful", this process introduces generally useful tools, and
may provide new insights.

'ABC';'DE' "boxes" the two lists of letters, and combines them
in a two-element list. The expression {'ABC';'DE' produces a
"catalog" by combining each element of the first list with each
of the second, in a process also known as the Cartesian Product.
Thus:
)
'ABC';'DE'

{'ABC';'DE'

NB. =========================================================
Lab Section

Moreover, the catalog function { generalizes this to any number of
lists, as illustrated below:
)
{'ABC';'DE';'FGHI'

NB. =========================================================
Lab Section

The function ~. applies to a list to obtain its "nub", that is,
the list of distinct elements; the function d=:]-:~.
matches this nub with the original list to determine if the
elements of the original list were distinct; and seld=:d # ] selects the list
if the elements are distinct. For example:
)
d=:]-:~.    NB. Test if distinct

seld=:d # ] NB. Select if distinct

~. 'ABB'    NB. Nub suppresses second 'B'

d 'ABB'

seld 'ABB'  NB. Gives an empty list since not all distinct

seld 'ABC'  NB. Gives the original list

NB. =========================================================
Lab Section

We now apply seld to each element of the table of two elements
from a list of three letters:
)
TABLE=:{'ABC';'ABC'

TABLE

seld each TABLE

NB. Continued

NB. =========================================================
Lab Section
)
,seld each TABLE            NB. Ravel the table to form a list

(,seld each TABLE)-.<''     NB. Remove empties (<'')

3 2$(,seld each TABLE)-.<'' NB. Rehape

NB. =========================================================
Lab Section

We now repeat the process on the table appropriate to Example 1:
)
TABLE5_3=:{'ABCDE';'ABCDE';'ABCDE'

12 5$(,seld each TABLE)-.<''

NB. =========================================================
Lab Section

Example 4 (page 114) introduces the factorial function, written in the
form n!. We will instead use !n, placing the function BEFORE its
argument, in the manner common to all other functions of one argument.

We will also use the ! in a function of two arguments, which we might
call "outof", since 3!5 gives the number of ways of choosing 3 things
out of 5. This is also called the binomial coefficient function, and
the expression will supplant the use of "surrounding parentheses".

The following examples illustrate an important relation between
the factorial and the binomial coefficients.
)

m=:5
n=:8

m!n

!n

!m

!n-m

(!n) % (!m) * (!n-m)

NB. =========================================================
Lab Section

The following expressions show tables of the binomial coefficient function:
)
y=:i.6
y

y !/ y

y !border y

color y !/ y

NB. =========================================================
Lab Section

We will define a function K for the "n to k factors" of
page 113, and show its function table and its relation
to the binomial coefficients function:
)
i.3

4-i.3

*/4-i.3

K=:*/@([ - i.@]) "0

4 K 3

x K border x=:i.5 NB. See table page 119

4 K 4

!4

NB. =========================================================
Lab Section

The operator ~ commutes its argument, in that x f~ y
is equivalent to y f x. Moreover, the monadic use f~ y is equivalent
to y f y, and ~ is said to be "reflexive".

In particular, K~ y is equivalent to y K y, and K~ is therefore
the factorial.

The inverse of the function table for K is also interesting,
and should be compared to the inverse of the binomial coefficients table:
)
K~ x

!x

m=: x: x K/ x            NB. extended precision

m;(%.m);(m mp %.m)

NB. =========================================================
Lab Section C. Subsets of a Set of Distinct Objects

The function A. produces anagrams, or permutations of its
argument. For example:
)
x=:0 1 2

y=:'ABC'

0 A. x

1 A. x

0 1 2 3 4 5 A. x

(i.!#y) A. y

NB. =========================================================
Lab Section

Repeat the preceding panel using the four-element list y=:'ABCD'.
Then color the final result, and use the pattern to explain
why there are 4*3*2*1 distinct permutations of order 4.

It may help to maximize the color display by clicking the mouse
on the middle button in the upper right corner:
)

NB. =========================================================
Lab Section

We will now generate a corresponding table of 120 rows
and 5 columns for the list 'ABCDE', take the first three
elements of each row, apply the nub to suppress duplicates,
box each row, and reshape the boxes to get
a 5 by 12 table.

This table contains the same entries as the table of page 123,
but arranged so that each of the five rows begins with one of
the letters of the list 'ABCDE':
)
q=:(i.!#y) A. y=:'ABCDE'

$r=:3 {."1 q

$s=:~.r

$t=:<"1 s

5 12$t

NB. =========================================================
Lab Section D. Properties of k!n

We will test the steps in the proof of Pascal's
Identity (page 133) for a specific case of the
arguments k and n. They should be repeated for
other cases:
)
k=:3

n=:5

(k!n)+((k+1)!n)

(k!n)+(((n+1)-(k+1))%(k+1))*(k!n)

(1+(n-k)%(k+1))*(k!n)

((n+1)%(k+1))*(k!n)

NB. =========================================================
Lab Section


The case 1 e) of Exercises 4.5 (page 134) may be written as follows:
)
+/1 2 3 4 ! 4

NB. =========================================================
Lab Section E. Permutations of Objects That Are Not All Distinct

The table of Example 1 on page 138 will be generated by
first obtaining all permutations of 'AABBB', and then applying the nub. Thus:
)
~.(i.120)A. 'AABBB'

NB. =========================================================
Lab Section

The following is the general form for the number of permutations given
in Example 3 on page 139:
)
f=:(!@(+/))%*/@:!

f 3 4 5

NB. =========================================================
Lab Chapter SEQUENCES AND THE BINOMIAL THEOREM
NB. =========================================================
Lab Section A. Introduction

"...a sequence is specified by a rule that tells how to calculate
each term." (FM page 158). In other words, a sequence is a function
of its indices. The accompanying example may therefore be defined
as the function t=:(2: * ]) - 2: as shown below:
)
t=:(2: * ]) - 2:

t 1

t 2

t 1 2 3 4 5

t 1+i.10

a=:(_1:^])*]%(]+1:) NB. The sequence of Example 1

a 1

a 1+i.10

a 1+i.10x

NB. =========================================================
Lab Section B. Recursion

"The sequence in Example 2 is defined recursively; that is, each term
is calculated from the previous term." (page 159). The first term must, of course,
be otherwise specified, and in this case it is specified by the function 1:.

The definition of the sequence t is therefore based on
the "recursion" case1=:(2: * (t@(] - 1:))) + 4:, on the starting
function case2=:1:, and on cond=:(] = 1:), a
function that determines which of these two is to be used.

This is expressed by using the "tie" operator ` to join the cases, and
the "agenda" operator @. to perform the selection. Finally, "0 is
applied to make t apply to each element of a list argument:
)
case1=:(2: * (t@(] - 1:))) + 4:

case2=:1:

cond=:(] = 1:)

t=:case1`case2@.cond"0

t 1

t 2

t 1 2 3 4 5 6 7 8 9 10

NB. =========================================================
Lab Section C. Types of Sequence: Arithmetic and Geometric

Sequences are classified according to how they "progress",
that is, how each term is related to the one that precedes it.
For example:
)
r=:t 1 2 3 4 5 6 7 8 9 10 NB. The recursively defined sequence

r

}. r             NB. Drop the first element

}: r             NB. Drop the last

as=:(}. - }:) r  NB. Difference shows relation (an arithmetic sequence)

as

gs=:(}. % }:) as NB. Ratio shows that as is geometric

gs

NB. =========================================================
Lab Section

We will now define functions for determining differences
and ratios and will illustrate their use. Apply them
for analyzing other sequences:
)
diff =:}. - }:

ratio=:}. % }:

diff r

ratio diff r

NB. =========================================================
Lab Section

The functions diff and ratio are also useful for discerning
the patterns in lists presented in lieu of a precise definition
of a sequence. For example:
)
diff _7 _4 _1               NB. Example 4, page 160

Ex5=:(%:3),1,(1% %:3),(1%3) NB. Example 5, page 160

Ex5

ratio Ex5

*: ratio Ex5                NB. Square ratios

%*: ratio Ex5               NB. Reciprocal square

ratio _1 1 _1 1             NB. Exercises 5.1 a)

ratio 1 8 27 64             NB. b)

ratio 1r2 1r6 1r18 1r54     NB. c)

ratio 1r2 2r3 3r4 4r5       NB. d)

NB. =========================================================
Lab Section

The sequences of Exercises 5.2 b) and d) are neither geometric
nor arithmetic. However, the following expressions
reveal patterns:
)
diff 1 8 27 64             NB. b)

diff diff 1 8 27 64 NB. Promising, but needs a longer list of cubes

x=:1 8 27 64 125 216 343

diff x

diff diff x

diff diff diff x    NB. 3rd diff is the 3rd derivative of the cube

diff diff diff diff x

1r2 2r3 3r4 4r5     NB. d)

z=:1+i.8

z % 1 + z

NB. =========================================================
Lab Section D. Domain Restrictions

We will first recall the sequence a defined for Example 1,
and show that it applies not only to the indices 1 2 3 4 5, but
also to non-indices such as 1 2 3 4 5-5 and 1 2 3 4 5%5.

This makes perfect sense, but in discussing sequences we usually
assume (perhaps tacitly) that their domains are limited to the
counting numbers. Thus:
)
a=:(_1:^])*]%(]+1:) NB. The sequence of Example 1

a 1 2 3 4 5

1 2 3 4 5-5

a 1 2 3 4 5-5

1 2 3 4 5%5

a 1 2 3 4 5%5 NB. Results are complex numbers

NB. =========================================================
Lab Section

Each of the following functions give 1 for arguments in a specified
domain, and 0 for arguments not in the domain:
)
p=:]>0: NB. Domain of positive numbers

i=:]=<. NB. Domain of integers (<. is "integer part")

pi=:p *. i NB. *. is "and" function

x=:(i:5)%2

decimal x

p x

i x

pi x

allpi=:*./@pi NB. True if all elements of a list are positive integers

allpi x

allpi 3 2 1 4

NB. =========================================================
Lab Section

We will now use the function sde=:'Sequence Domain Error'"_ together
with the function a to define a function sa that is a proper sequence
function (in the sense that its domain is limited to the
positive integers).

A finite sequence may be treated by adding a restriction
of the form ]<M"0 or ]<5"0:
)

sde=:'Sequence Domain Error'"_

sa=:sde`a @. allpi

sa 1 2 3 4 5

a 0 1 2 3 4

sa 0 1 2 3 4

sa 1r2 1 2 3 4

NB. =========================================================
Lab Section E. Summation Notation

The four cases of Example 1 of Section 5.2 are shown below:
)
+/3^2+i.1+8-2 NB. Number of elements is 1+ difference of limits

+/3^2+i.7     NB. or more simply

+/1+2*1+i.6

+/(3+i.3)!5

+/2"0 (1+i.7) NB. 2"0 is the constant function 2

NB. =========================================================
Lab Section

The following treats the general case in Example 4, using
functions a, b, and c:
)
a=:] ! 5"0
b=:] ^ 2"0
c=:3"_      NB. A scalar constant function

a i=:1+i.n=:7
+/a 1+i.n

b i
+/b i

c i
+/c i

(a+b) i
+/(a+b) i

(+/a i)+(+/b i)

(+/(c i)*(a i)),((c i)*(+/a i))

NB. =========================================================
Lab Section F. Sums of Arithmetic and Geometric Sequences

We will use some of the foregoing results in an informal proof that
the sum of the first n counting numbers is n*(n+1)%2 or, more exactly,
that twice the sum is n*(n+1):
)
]s=:1+i.n=:7 NB. List of first n counting numbers

]rs=:|.s     NB. List in reverse order

s+rs         NB. They add to a list of n constants n+1

+/s+rs       NB. Whose sum is therefore n*n+1

n*n+1        NB. As may be seen

(+/s),(+/rs) NB. Sums are equal (order not relevant in addition)

2*+/s        NB. Double sum

(+/s)+(+/rs) NB. Is the same as the sum of equals

+/s+rs       NB. Which equals the sum over the added lists

NB. =========================================================
Lab Section

Use these methods to determine closed expressions for the sum of the first
n integers (which begin at 0 rather than 1), and for the sum of the first n
odd numbers.
)

NB. =========================================================
Lab Section G. Limits of Sequences

The first example in Section 5.4 concerns the sequence t=:1r2&^
)
t=:1r2&^
t 0 1 2 3
x=:i.9
t x
decimal t x

plot x;t x

NB. =========================================================
Lab Section

 We will define PLOT as plot with
 "sticks" as well as lines, and use
 it to provide more readable graphs.

 We will also use the adverb \ which
 applies its argument verb to each
 prefix of the argument list. For
 example, the verb +/\ gives subtotals:
)
x

+/x

+/\x

+/\t x

decimal +/\t x

PLOT=:'line,stick'&plot

PLOT t x

NB. =========================================================
Lab Section

The sum +/t i.n appears to be approaching 2 as n increases:
)
+/t i.18

decimal +/t i.18

2-1r2^17         NB. An equivalent closed form

+/t i.19         NB. Another sum

decimal +/t i.19 NB. whose decimal approximation is 2

NB. =========================================================
Lab Section

Some further cases from Example 1 (page 177):
)
c=:_1r3&^ NB. part c

3 5$decimal +/\ c i.15

e=:_1&^   NB. part e

3 5$decimal +/\ e i.15

f=:1&^    NB. part f

3 5$decimal +/\ f i.15

NB. =========================================================
Lab Section H. The Binomial Theorem

In the box on page 183 of FM, binomial coefficients are
denoted in the form n above r, all enclosed in parentheses.
We will use r ! n, the result being the number of ways that
r distinct things can be chosen from n distinct things. It is also called
the binomial coefficient r of order n.

We will also use the commuted form n !~ r. Bordered tables of
the functions ! and !~ are shown below. It should be noted that
the zero entries are significant. For example, 4!3 is 0,
because there are 0 ways of choosing 4 things from 3. Nevertheless,
they are commonly ignored (as in Pascal's Triangle), and we
say that the 4-element list 1 3 3 1 represents the binomial
coefficients of order 3.
)
3!5  NB. The number of ways of choosing 3 things from 5

i=:0 1 2 3 4 5 6 7

(i !border i) ,. (i !~border i)

NB. =========================================================
Lab Section

In the same box, the Binomial Theorem is stated by expressing
the power (x+y) ^ n as a sum. We will treat the simpler case where
y is 1, thus simplifying the given expression for (x+y)^n to a weighted sum
of powers of x, the weights being the binomial coefficients:
)
x=:5
n=:3

(x+1)^n

e=:0 1 2 3 NB. Exponents for powers of x

x^e

c=:e!n     NB. Binomial coefficients

c*x^e

+/c*x^e

((x+1)^n) = (+/c*x^e)

NB. =========================================================
Lab Section

Such a weighted sum of declining powers of x is also called a
polynomial, a function two arguments: the coefficients, and
the argument x. We will denote the polynomial function by poly,
as illustrated below:
)

3 2 4 poly x             NB. Equivalent to the following sum

(3*x^2)+(2*x^1)+(4*x^0)

1 2 1 poly x             NB. Binomial coefficient of order 2

(x+1)^2                  NB. Equivalent to 1 2 1 poly x

(1 3 3 1 poly x),((x+1)^3)

(1 5 10 10 5 1 poly x),((x+1)^5) NB. Order 5

(1 2 1 poly x)*(1 3 3 1 poly x)  NB. Product of polynomials

((x+1)^2)*((x+1)^3)              NB. Series of equivalent expressions

(x+1)^(2+3)

1 5 10 10 5 1 poly x             NB. Order 2+3 is product of orders 2 and 3

NB. =========================================================
Lab Section

The foregoing sequence illustrates the fact that the
product of two polynomials with binomial coefficients
of orders 2 and 3 is equivalent to the polynomial
with the binomial coefficients of order 2+3.

In multiplying polynomials, each term is multiplied by each
term and these products are then summed. The product of a pair of terms is the
product of their coefficients with the product of their
powers of x, which is x to the sum of their exponents.

If the coefficients are the lists c and d, the products of
the coefficients are contained in the table c */ d, and the
products along each diagonal (sloping like the line /) are
coefficients of the same power of x. The sums along these
diagonals (+//.) give the coefficients of the
product polynomial. For example:
)
c=:1 2 1
d=:1 3 3 1
c*/d
cd=:+//.c*/d NB. Sums over 1 and 3 2 and 3 6 1 and 1 6 3 and 2 3 and 1
cd
((c poly x)*(d poly x)),(cd poly x)

NB. =========================================================
Lab Section

The foregoing suggests the definition of the "polynomial
product" function pp=:+//.@(*/), whose use is illustrated
below:
)
pp=:+//.@(*/)

c pp d

2 3 1 pp 4 2 1 3 NB. An arbitrary pair of coefficients

2 3 1 poly x

4 2 1 3 poly x

(2 3 1 poly x) * (4 2 1 3 poly x)

((2 3 1 pp 4 2 1 3) poly x)

c pp d pp c      NB. Repeated use of pp (gives bin coeff of order 2+3+2)

NB. =========================================================
Lab Section

Since 1 1 poly x is equivalent to x+1, the product 1 1 pp 1 1 gives
coeffients of the polynomial equivalent to (x+1)*(x+1). Repeated
products of the form 1 1 pp 1 1 pp 1 1 give the successive
binomial coefficients:
)
1 1 poly x

x+1

1 1 pp 1 1

(1 1 pp 1 1) poly x

(x+1)*(x+1)

1 1 pp 1 1 pp 1 1

1 1 pp 1 1 pp 1 1 pp 1 1

1 1 pp 1 1 pp 1 1 pp 1 1 pp 1 1

b4=:1 4 6 4 1

1 1 pp b4

NB. =========================================================
Lab Section

The diagonal sums of the table 1 1 */ b4 give 1 1 pp b4,
and an examination of this table shows that the result is
equivalent to the list b4,0 added to the list 0,b4. Thus:
)
1 1 pp b4

1 1 */ b4

b4,0

0,b4

(b4,0)+(0,b4)

next=: ,&0 + 0&, NB. Gives binomial coefficient of next order

next 1

next next 1

next next next 1

next 1 5 10 10 5 1

NB. =========================================================
Lab Section I. Finding Terms in Binomial Expansions

In the binomial expansion of Section 5.6 of FM (page 188), the terms in the
expansion of (x+y)^n are products of binomial coefficients
with decreasing powers of x (as in the simpler case (x+1)^n) also
multiplied by increasing powers of y. For example:
)
x=:2
y=:5
n=:3
(x+y)^n

dpx=:(x^|.i.n+1) NB. Decreasing powers of x
dpx

ipy=:(y^i.n+1)   NB. Increassing powers of y
ipy

d=: (i.n+1)!n    NB. Binomial coefficients
d

d*dpx*ipy

(+/d*dpx*ipy),((x+y)^n)

NB. =========================================================
Lab Section J. Sums Involving Binomial Coefficients

We will use the binomial coefficient table bc=:i !/ i=:i.5 to
illustrate cases a) and b) of Example 1. Since +/bc sums the columns (that
is, adds the row vectors), then +/bc gives case a). Since -/a gives
the alternating sum of each column, it provides case b). Thus:
)
i=:i.5
bc=:i !/ i
bc

+/bc

2^i

_1^i

(_1^i)*i

+/(_1^i)*i

-/i

-/bc NB. Note that the first result is 1, NOT 0 as stated in FM.

NB. =========================================================
Lab Section

The expression +/0 1 2 3 4 * 1 3 3 1 0 gives a weighted sum
of the binomial coefficient of order 3. Moreover, if bc is
a function table of  binomial coefficients, then the matrix
product bc mp bc gives a collection of such weighted sums,
as illustrated below:
)
0 1 2 3 4 * 1 3 3 1 0
+/0 1 2 3 4 * 1 3 3 1 0

bc=:(i.5) !/ (i.5)
bc

bc2=:bc mp bc
bc2

bc rsub 2   NB. Row 2 of bc
bc csub 4   NB. Col 4 of bc
+/(bc rsub 2)*(bc csub 4)
bc2 sub 2 4 NB. Element in row 2 col 4 of bc2

NB. =========================================================
Lab Section

Moreover, a simple closed form can be obtained for bc2 by
using the subtraction table st=:(i.5)-~/(i.5) as follows:
)
st=:(i.5)-~/(i.5)
st

2^st

bc*(2^st) NB. Element-by-element product

(bc*(2^st));bc2

NB. =========================================================
Lab Section

Further matrix products produce weighted sums of binomial
coefficients that have similar closed forms:
)
bc3=:bc2 mp bc
bc4=:bc3 mp bc
bc5=:bc4 mp bc

bc;bc2;bc3;bc4;bc5

bc * 4 ^ st NB. Compare with b34

NB. =========================================================
Lab Section K. Sums of Other Sequences

We will illustrate #3 of Problems 5.8 of FM:
)
k=:1+i. n=:6
k

theta=:1r10

sin=:1&o.
cos=:2&o.

(2*k)-1

((2*k)-1)*theta

sin ((2*k)-1)*theta

+/sin ((2*k)-1)*theta

(1-cos 2*n*theta)%(2*sin theta)

NB. =========================================================
Lab Chapter PROBABILITY
NB. =========================================================
Lab Section A. Probability Models

We will use lists to represent the set and the associated probabilities,
and combine them into a single two-element list to represent a
probability model:
)
S=:1 2 3 4 5 6
p=:1 1 1 1 1 1 % 6
A=:2 4 6
B=:1 2 3 4 5

3 7 e. S NB. e. is the membership function (epsilon is used in math)

S e. A         NB. Identify which of S belong to A
(S e. A) # i.6 NB. Select from right argument
(S e. A) # p   NB. Select corresponding probabilities

+/(S e. A) # p NB. Probability of A in S

S1=:S;p
S1

prob=:+/@((>@{.@[ e. ])# >@{:@[)

S1 prob A

S1 prob 1 2 3 4 5 NB. List B in FM

S1 prob 5 6 7 8   NB. 7 and 8 are not in the set

NB. =========================================================
Lab Section

Certain conditions are imposed on a probability model: the elements of the set
must be distinct, the number of elements must equal the number of probabilities,
the probabilities must be positive, and must be complete (that is, sum to 1).
We combine these in a test as follows:
)
distinct=:(] -: ~.)@>@{.

number=:#@>@{. = #@>@{:

positive=:and/@(>&0 @ >@{:)

complete=:=&1@(+/)@>@{:

and=:*.

test=:distinct and number and positive and complete

S;p

test S;p

test S;p-0.1

test 1 2 3 4 5 1 ; p

NB. =========================================================
Lab Section

Example 3 of FM (page 207) introduces the notion of the "complement" of
a set C with respect to a "complete" set S. This is given by the function
"less" (denoted by -.):
)
S=:1 2 3 4 5 6
C=:2 4 6

S -. C

C -. S

NB. =========================================================
Lab Section

Item 3 of Exercises  6.1 of FM (page 209) introduces the notion
of a computer program to generate random numbers within a given
range, with equal probabilities. This is provided by two functions:
? for general use, and ?. for "repeatable sequences". The latter
are important in providing examples, and in developing functions
for the treatment of probabilities:

It is important to use randomly generated sequences (from dice or
from computers) to test probability functions, because personal
choice of examples may well be biased toward those that work, and
may fail to disclose problems that might be revealed by randomly chosen
arguments:
)
i.6

? 6          NB. Random choice from the population i.6

? 6 6 6 6 6  NB. Five random choices

? 6 6 6 6 6  NB. Repetition leads to different random results

?. 6 6 6 6 6 NB. Repeatable generator

?. 6 6 6 6 6 NB. Gives same results each time

NB. =========================================================
Lab Section B. Markov Chains

The first example of a Markov Chain (evaluated on
page 255) will be expressed in terms of beg=:1r2 1r2 (the beginning
values), and the prescribed probability matrix mc:
)
beg=:1r2 1r2

mc=:2r3 3r4 ,. 1r3 1r4

mc

+/"1 mc          NB. Check that row sums are 1

beg mp mc        NB. One step of matrix product

+/ beg mp mc     NB. Results sum to 1

q=:beg mp mc mp mc mp mc

q                NB. Result of three steps

+/q

decimal q        NB. compare this decimal value with page 255

NB. =========================================================
Lab Section

The function step=:mp&mc applies one multiplication by mc,
and therefore defines a single step of the Markov process.

We will use this, together with step ^: n to apply n steps.
This will allow us to see how this particular Markov Chain
converges quickly to a fixed value:
)
step=:mp&mc

step beg

step step step beg

step^:3 beg

decimal step ^:3 beg

decimal step ^: 0 1 2 3 4 5 6 7 beg

NB. =========================================================
Lab Chapter RANDOM VARIABLES
NB. =========================================================
Lab Section A. Introduction

We will represent the sample space used on page 265 of FM by
the columns of a matrix S, and determine the probabilities
of the maxima of elements as follows:
)
S=:1 2,.1 3,.1 4,.2 3,.2 4 ,.3 4
S               NB. Columns of S represent the set

]max=:>./S      NB. maxima of pairs

~.max          NB. List of distinct maxima

classify=:(~.max)=/max

classify        NB. Classify by comparison with distinct members

numberinclass=:x:+/"1 classify NB. Sum rows of classification

numberinclass

+/numberinclass NB. Total number

numberinclass%+/numberinclass  NB. Probabilities of each class

NB. =========================================================
Lab Section

The foregoing can be modified to effect Example 1 (page 266).
S is now given by a "catenation table" using ,"0 to catenate each pair,
modified by applying ,/ to reduce the rank-3 array to a matrix, and
|: to transpose it to represent S by columns. Moreover, the maxima are
replaced by sums. In comparing the final results with FM, note that they
are expressed in lowest form (e.g. 1r18 instead of 2r36):
)
S=:|:,/die,"0/ die=:1 2 3 4 5 6
S               NB. Columns of S represent the set
]sum=:+/S       NB. sums of pairs
~.sum           NB. List of distinct sums
classify=:(~.sum)=/sum
classify        NB. Classify by comparison with distinct members
numberinclass=:x:+/"1 classify NB. Sum rows of classification
numberinclass
+/numberinclass NB. Total number
numberinclass%+/numberinclass  NB. Probabilities of each class

NB. =========================================================
Lab Section

Since the distinct classes are given by dc=:~.sum, the expression
dc<6 gives a boolean result that can be used to select all members
of the probabilities in this classs, and a final summation gives the result for Example 1
(page 267):
)
dc=:~.sum

dc

dc<6

(numberinclass%+/numberinclass)

(dc<6) # (numberinclass%+/numberinclass)

+/(dc<6) # (numberinclass%+/numberinclass)

NB. =========================================================
Lab Section

 If prob=:(numberinclass%+/numberinclass)
 is the list of probabilities for the sums
 of two dice, then plot prob provides a
 plot of them. Moreover, hist prob
 provides a histogram, or "stick" plot,
 as suggested in Example 3 (page 269).
 Press the Esc key to remove the histogram
 window so that you can proceed:
)
prob=:(numberinclass%+/numberinclass)

hist prob

NB. =========================================================
Lab Section B. Expected Value

The foregoing calculations led to the results dc (for the distinct
classes of sums of pairs of dice) and prob (for the corresponding
probabilities). The expected value is therefore given by the sum
of their products.

We will also produce a histogram of the product dc*prob:
)
dc

prob

dc*prob

+/dc*prob

hist dc*prob

NB. =========================================================
Lab Section

As already discussed in Chapter 6, the uniform random variable
Z of Example 4 (page 277) may be provided by either of two expressions:
? 10, or (using the repeatable form) by ?.10. For example:
)
?10

?10

?.10

?.10

?.10 10 10 10 10 10 10 10 10 10 10 10 10 10 10

NB. =========================================================
Lab Section C. Standard Deviation

The two systems described on page 283 may be represented as follows,
and their expected values are shown to be the same:
)
S1=:5 6 7
p1=:1r3 1r3 1r3

S2=:3 4 5 6 7 8 9
p2=:1%7 7 7 7 7 7 7

S1*p1

+/S1*p1

S2*p2

+/S2*p2

NB. =========================================================
Lab Section

The standard deviation is the square root of the the expected value
of the square of the given values less their expected value. We will
begin with calculation of the variance, which iws defined as the
square of the standard deviation:
)
d1=:S1-+/S1*p1 NB. Differences from the expected value
d1
sq1=:*:d1      NB. Their squares
sq1
var1=:+/sq1*p1 NB. Their variance
var1
sd1=:%: var1   NB. The standard deviation
sd1

NB. =========================================================
Lab Section

Similarly for the second system:
)
d2=:S2-+/S2*p2 NB. Differences from the expected value
d2
sq2=:*:d2      NB. Their squares
sq2
var2=:+/sq2*p2 NB. Their variance
var2
sd2=:%: var2   NB. The standard deviation
sd2

NB. =========================================================
Lab Section D. Hypergeometric Random Variables

We will define a function hg, based on the boxed definition
in Example 1, page 202, using a list left argument to provide the
parameters N, A, and n, and the right argument for k.

To this end, we will first define functions N and A and n and k
to select the parameters:
)
N=:0&{@[ NB. The index function { selects (using 0 as first index)
A=:1&{@[
n=:2&{@[
k=:]

hg1=:k!A
hg2=:(n-k)!(N-A)
hg3=:n!N

hg=:hg1*hg2%hg3

10 3 4 hg x=:0 1 2 3 4 5 6 NB. Results are in reduced form (1r6 for 5r30)

+/10 3 4 hg x              NB. Sum is 1

decimal 10 3 4 hg x        NB. Decimal approximations

NB. =========================================================
Lab Section E. Binomial Random Variables

We will use the boxed definition in Example 1 (page 300)
as the basis for the definition of
a function brv whose list left argument specifies
the number of trials n, and the probability of success p.

Note that p"_ is the function whose result is the constant value p:
)
n1=:0&{@[
p1=:1&{@[
k1=:]

brv=:(k1 ! n1) * (p1"_ ^ k1) * (1"_ - p1"_) ^ (n1 - k1)

3 1r2 brv x=:i.10

+/3 1r2 brv x=:i.10

decimal 3 1r2 brv x=:i.10

4 1r2 brv x

4 1r10 brv x

+/4 1r10 brv x

decimal 4 1r10 brv x

NB. =========================================================
Lab Section F. The Binomial Approximation to the Hypergeometric Probability Function
)
y1=: 50 25 5 hg x=:0 1 2 3 4 5

y2=: 5 1r2 brv x

>y1;y2 NB. Matrix  of results

(decimal y1),.(decimal y2)

plot x;>y1;y2

NB. =========================================================
Lab Section

We may also use PLOT to provide a plot that includes the
vertical lines at vertices as well as the lines that join them:
)
PLOT x;>y1;y2

NB. =========================================================
Lab Chapter STATISTICS AND PROBABILITY
NB. =========================================================
Lab Section A. Histograms

The use of the function hist to produce simple histograms was
introduced in early sections of
Chapter 7. We will now review
those facilities that are useful
in displaying the properties of
mathematical results:

 hist  Which produces a histogram

 plot  Which produces a simple graph of its argument.

 PLOT  Which adds vertical lines to the graph

 surf  Which joins corresponding points in a collection of functions to produce a surface plot.

When using several windows, it may be more convenient to use Alt Tab (or the mouse)
to switch focus from the window to the main session. This allows successive
windows to display. To finally remove the window, click on it to give it focus before pressing Esc.
)

NB. =========================================================
Lab Section

 We will begin by computing three
 results of the sine function:
)
x=:1r5*i.11

y1=:sin x
y2=:sin x+1r5
y3=:sin x+2r5

>y1;y2;y3

hist x;y1

NB. =========================================================
Lab Section
)
plot x;y1

NB. =========================================================
Lab Section
)
PLOT x;y1

NB. =========================================================
Lab Section
)
y1;y2;y3

surf >y1;y2;y3

NB. =========================================================
Lab Section
)
color >y1;y2;y3

NB. =========================================================
Lab Section

Barcharts of the form shown at the bottom of page 322 may
be made by coloring comparison tables, as illustrated below:
)
a=:i.10
a
b=:10-2 3 3 4 4 4 0 0 3
b

a</b

color a</b

NB. =========================================================
Lab Section B. Means and Medians

The mean is defined as the sum divided by the number of items. Thus:
)
mean=:+/ % #

mean 3 1 4 2

rand=:?. 16#10

rand

mean rand

decimal mean rand

NB. =========================================================
Lab Section

For an odd number of items, the median is the middle
item in the sorted list. For an even number, it is
the mean of the two middle items.

We will first determine the number of items to
strip from each end in order to leave the middle item or items, and then
take their mean. Thus:
)
number=:<:@>.@-:@#    NB. Decrement ceiling of half of # of items

strip =:-@[ }. [ }. ] NB. Negative drop (from tail) of drop from front

sr=:sort rand

rand;sr

number sr                  NB. Number to be removed from each end

(number sr) strip sr       NB. Removal

(reduce=:number strip sort) rand

(median=:mean@reduce) rand

(number sr,20) strip sr,20 NB. Case of even number of items

NB. =========================================================
Lab Section C. Standard Deviation
According to the definition of standard deviation
on page 362, we subtract the mean
of a list from the list to get the normalized
list (whose mean is zero), sum the squares of its elements,
divide by one less than the number of elements, and
finally take the square root. Thus:
)
normal=:] - mean

p363=:82 68 39 72 94 NB. Example on page 363

normal p363

mean normal p363

std=:%:@(+/@(*:@normal) % <:@#)

std p363             NB. Compare with example on page 363

NB. =========================================================
Lab Section D. Normal Random Variables

We provide the Table of Normal Probabilities of page 371 as
the table TNP. Rows, columns, and elements from it may be
selected for use in examples and exercises as illustrated
below:
)
TNP rsub 1 2 NB. First two rows

TNP csub 1 2 NB. First two columns

NB. =========================================================
Lab Section

A particular element of TNP can be selected using sub, and a
formatted version with a uniform 4 digits following the decimal
may be obtained as illustrated below. Moreover, the "negative"
table of page 370 may be obtained by reversing the order of
the rows of table 1-TNP:
)
TNP sub 2 3 NB. Element in second row and third column

(0j4 ": TNP) rsub 1 2

(|. 1-TNP) rsub 1 2

NB. =========================================================
Lab Section E. The Normal Approximation to Binomial Probability Functions

Compare the results of using TNP (the table of normal probabilities)
and brv (the binomial random variables function.
)

NB. =========================================================
Lab Chapter MATHEMATICS OF FINANCE
NB. =========================================================
Lab Section A. Interest

Example 1 may be expressed as follows:
)
1000 * (1+10%100)^0 1 2 3

decimal 1000 * (1+10%100)^i.11

NB. =========================================================
Lab Section

Example 3 may be expressed as shown below, and the results show
that the accumulated amount exceeds 1000 after year 7.
)
decimal 5000*(1+10%100)^i.11

NB. =========================================================
Lab Section

The present value of Example 5 may be obtained as follows:
)
10000 * (1+(11.5%2)%100)^ -3*2

NB. =========================================================
Lab Section B-C. Annuities

Example 1 may be treated as follows:
)
r=:1+8%100

investments=:1000 * r ^ 0 1 2 3 4

investments              NB. Display values

+/investments            NB. Total investments

1000*((r^5) - 1) % (r-1) NB. Alternate computation

NB. =========================================================
Lab Section D. Mortgages

The calculations in Example 1 are given below:
)
i=:(1.05^1%6)-1
i

90000*(1+i)^240 NB. Accumulated value

(90000*i*(1+i)^240)%(((1+i)^240)-1) NB. Monthly payment

NB. =========================================================
Lab Section E. Contingent Payments

The calculation of the repayment in Example 1 may
be expressed as follows:
)
x=:10000%((1.11^_1)*0.9)

x

NB. =========================================================
Lab Section F. Mortality Tables and Life Annuities

The function mtf gives the function f of the mortality
table for males (page 437). Its use is illustrated below.

Since mtf i.106 gives all entries, it should sum to
exactly 1, but does not. The discrepancy shown in this
sum will be reflected in other results (such as the survivor function
S) derived from f.

Since mtf is defined in terms of the integer list mtt,
the corresponding discrepancy appears in it as well:
)
mtf 0 1 2 3 4

+/ mtf i.106

+/mtt

NB. =========================================================
Lab Section

We now define the survivor function S, and
use it together with mtf to produce the first few
entries of the table on page 437.

You may use the argument i.106 to produce the entire table:
)
S=:+/@mtf@(}.&(i.106))"0

t437=:(],.mtf,.S)

t437 0 1 2 3

t437 ,4

NB. =========================================================
Lab Section G. Life Insurance

The probability of death given in the last block
of the table in Example 1 is a function of two
arguments -- the age at which a man is still alive,
and the age to which he might survive.

For the expected present value, these probabilities
are multiplied  by negative powers of the interest
rate, and then summed to give the result shown in the text:
)
pod=:mtf@] % S@[

45 pod 45 46 47 48 49

50000*+/(1.07^-1 2 3 4 5)*45 pod 45 46 47 48 49
