J Labs

A J Introduction

(1 of 95) J - Introduction

J is executable mathematical notation.

The fourteen chapters of this lab illustrate its use in experimenting with mathematical ideas in a variety of topics.

To clarify ideas, enter your own experiments (which you may do at any point).


In [ ]:
2+3

In [ ]:
x=: 2

In [ ]:
y=:3

In [ ]:
x+y

(2 of 95) Functions

There is a rich set of primitives.


In [ ]:
2 + 3

In [ ]:
2 - 3

In [ ]:
2 * 3

In [ ]:
2 % 3

In [ ]:
2 ^ 3

In [ ]:
2 ^ 0.5

In [ ]:
_2 ^ 0.5

In [ ]:
2 ^. 3

(3 of 95) Arrays

Functions apply to arrays.


In [ ]:
2 + 5 6 7

In [ ]:
2 3 4 * 5 6 7

In [ ]:
2 3 4 - 5 6 7

In [ ]:
2 3 4 % 5 6 7

In [ ]:
2 3 % 5 6 7    NB. error because arguments do not match

(4 of 95) Arrays (ctd)

Some functions make arrays.

i.n is a list of the first n integers.

s $ v makes an array of shape s using the elements v


In [ ]:
i. 7

In [ ]:
1 + i. 7

In [ ]:
2 ^ i. 7

In [ ]:
(i. 7) ^ 0.5

In [ ]:
3 5 $ 3 1 4 2

In [ ]:
x=:3 5 $ 3 1 4 2

In [ ]:
x * x

(5 of 95) Assignment

An array or function can be assigned a name by using =: (the copula).


In [ ]:
i. 7

In [ ]:
x=:i. 7

In [ ]:
x

In [ ]:
x ^ 2

In [ ]:
power=: ^

In [ ]:
x power 2

In [ ]:
x power 0.5

(6 of 95) Monadic or Dyadic

A function can be monadic or dyadic, depending on whether it applies to one argument (on the right) or to two (on the left and right).


In [ ]:
2 - 3   NB. Subtraction (dyadic)

In [ ]:
-3      NB. Negation (monadic)

In [ ]:
2 % 3   NB. Division

In [ ]:
% 3     NB. Reciprocal

In [ ]:
2 ^ 3   NB. Power

In [ ]:
^0 1 2  NB. Exponential

(7 of 95) More Primitives

The primitive functions include + - * % as well as ^ (power), ^. (log), > (greater than), >. (greater-of, or maximum), +. (or/GCD), *. (and/LCM), | (residue or modulo), etc.

All of these can be monadic or dyadic, and apply to arrays.


In [ ]:
2 ^ 3 4 5 6

In [ ]:
2 ^ 0.5 3 _5

In [ ]:
_2 ^ 0.5 6 7

In [ ]:
0 0 1 1 +. 0 1 0 1

In [ ]:
2 3 4 5 +. 10 20 30 40

In [ ]:
2 3 4 5 *. 10 20 30 40

In [ ]:
2 3 4 5 | 10 20 30 40

In [ ]:
2 3 4 5 <. 10 20 30 40

In [ ]:
2 3 4 5 >. 10 20 30 40

(8 of 95) Insert

Adverbs modify verbs (functions) to produce new verbs.

For example, the adverb / inserts its verb argument between the items of its argument.

Thus, +/ is summation and */ is product. These are the "big sigma" and "big pi" of conventional notation. Moreover, / can be applied to any function: >./ is maximum, <./ is minimum, +./ is or or GCD, *./ is and or LCM, etc.


In [ ]:
x=: 1 + i. 7

In [ ]:
x

In [ ]:
+/ x

In [ ]:
*/ x

In [ ]:
>./ x

In [ ]:
<./ x

In [ ]:
+./ x

In [ ]:
*./ x

(9 of 95) Table

If f is a verb (function), then f/ is a verb, and, like any other verb, it can be monadic or dyadic. The monadic meaning is "insert". The dyadic meaning is "table", that is, a function table.

Function tables are a good way to organize systematic experimentation on unfamiliar functions.


In [ ]:
x=:i.9

In [ ]:
x

In [ ]:
x +/ x

In [ ]:
x */ x

In [ ]:
x </ x

In [ ]:
x >/ x

In [ ]:
x >./ x

In [ ]:
x <./ x

In [ ]:
x +./ x

In [ ]:
x *./ x

In [ ]:
x |/ x

(10 of 95) Table (ctd)

The Hilbert matrix is a simple function on the addition table. As shown below, its pattern is more apparent in the extended precision (rational) domain.

Although Hilbert matrices are notoriously unstable under inversion, the matrix inverse (%.) gives an exact integer result (as shown below):


In [ ]:
x=:i.7

In [ ]:
x +/ x

In [ ]:
% 1 + x +/ x

In [ ]:
y=:i.7x   NB. The final x gives extended precision

In [ ]:
H=:% 1 + y +/ y

In [ ]:
H

In [ ]:
%. H

(11 of 95) Table (ctd)

The "triangle" of Pascal is an example of a function table, based on the binomial coefficient function ! .

An advantage of treating it as a table rather than as a triangle is that matrix operations (such as matrix inverse) can be applied to it.


In [ ]:
x=: i. 7

In [ ]:
x !/ x

In [ ]:
m=: x !/ x

In [ ]:
%. m       NB. The alternating binomial coefficients

In [ ]:
+/ m

In [ ]:
+/ %. m

(12 of 95) Prefix

Prefix is another adverb. f\ applies f to the prefixes of the argument.

The monad < (box) is helpful in understanding prefix.


In [ ]:
x=: 1+i.7

In [ ]:
x

In [ ]:
+/\ x    NB. Subtotals

In [ ]:
<\ x

In [ ]:
*/\ x    NB. Progressive products

In [ ]:
<./\ x

In [ ]:
>./\ x

In [ ]:
+./\ x

In [ ]:
*./\ x

(13 of 95) Permutations

The dyadic function x{y indexes y by x If p is a permutation p, then p{y permutes y by p.


In [ ]:
p=:9 ?. 9    NB. A random permutation

In [ ]:
p

In [ ]:
p { p

In [ ]:
p { p { p

In [ ]:
6 9$p

In [ ]:
{/ 6 9$p

In [ ]:
{/\ 6 9$p

(14 of 95) Permutations (ctd)

{/ (m,#p) $ p inserts { between m copies of the permutation, and computes the m-th power of p.

The corresponding prefixes, {/\ (m,#p) $ p, are the successive powers of p.


In [ ]:
p

In [ ]:
p{p

In [ ]:
p{p{p

In [ ]:
{/ 6 9 $ p

In [ ]:
{/\6 9 $ p

(15 of 95) Permutations (ctd)

C. p computes the cycles of the permutation p. The Least Common Multiple (*./) of the cycle lengths is the order of the subgroup generated by p.


In [ ]:
p

In [ ]:
C. p

In [ ]:
#&> C. p

In [ ]:
*./ #&> C. p

(16 of 95) Patterns: color - Addition Table

The pattern seen in an addition table can be emphasized by producing a window in which equal values in the table are assigned the same color.


In [ ]:
require 'plot viewmat'

In [ ]:
color =: viewmat

In [ ]:
x=:i. 5

In [ ]:
x +/ x

In [ ]:
color x +/ x

(17 of 95) Subtraction Table


In [ ]:
x -/ x       NB. Subtraction table

In [ ]:
color x -/ x

(18 of 95) Multiplication Table

When applied to a list of positive and negative integers, the multiplication table provides an interesting pattern.


In [ ]:
pn=: i: _3

In [ ]:
pn

In [ ]:
pn */ pn

In [ ]:
color pn */ pn

(19 of 95) Multiplication Table (ctd)

The monad * is called the "signum" or "sign" function. When applied to a multiplication table, it shows the pattern of positive and negative results produced by multiplication.


In [ ]:
pn

In [ ]:
*pn

In [ ]:
* pn */ pn

In [ ]:
color * pn */ pn

(20 of 95) Remainder Table

3 | 5 gives the "remainder" or "residue" on dividing 3 into 5. Study the following remainder table and (before advancing to the next panel), try to predict the appearance of coloring the 2-residue of the addition table given by 2 | (i.8) +/ (i.8).


In [ ]:
y=: 1 + i. 6

In [ ]:
y |/ y

In [ ]:
color y |/ y

(21 of 95) Checkerboard


In [ ]:
2 | (i.8) +/ (i.8)

In [ ]:
color 2 | (i.8) +/ (i.8)

(22 of 95) Fractals

Residues of binomial coefficient tables provide examples of fractals (which "replicate according to their own pattern").

This is illustrated in this and the next three panels.


In [ ]:
2 | (i.2) !/ (i.2)

In [ ]:
color 2 | (i.2) !/ (i.2)

(23 of 95) Fractals (ctd)


In [ ]:
2 | (i.4) !/ (i.4)

In [ ]:
color 2 | (i.4) !/ (i.4)

(24 of 95) Fractals (ctd)


In [ ]:
2 | (i.16) !/ (i.16)

In [ ]:
color 2 | (i.16) !/ (i.16)

(25 of 95) Fractals (ctd)


In [ ]:
3 | (i.16) !/ (i.16)

In [ ]:
color 3 | (i.16) !/ (i.16)

(26 of 95) Fractals (ctd)

This is the end of this chapter. To continue with the next chapter, advance as usual. But to select any other chapter, click on Chapters under the Studio menu.

(27 of 95) Patterns: Plots - Simple plot

The square function (*:) applied to a list x may be plotted against its argument as follows:


In [ ]:
require'plot'

In [ ]:
x=: i.5

In [ ]:
y=: *: x

In [ ]:
x;y

In [ ]:
plot x;y

(28 of 95) Stick and Line Plot

A plot that shows vertical lines to the argument axis may be produced similarly as follows.


In [ ]:
PLOT=: 'stick,line'&plot

In [ ]:
PLOT x;y

(29 of 95) Stick and Line Plot (ctd)

Combined plots of two or more functions are produced as follows.


In [ ]:
z=: %: x  NB. Square root

In [ ]:
x;>y;z

In [ ]:
PLOT x;>y;z

(30 of 95) Stick and Line Plot (ctd)

The sine and cosine functions may be plotted as follows.


In [ ]:
sin=: 1&o.

In [ ]:
cos=: 2&o.

In [ ]:
x=: 0.1 * i: 21

In [ ]:
x

In [ ]:
PLOT x;>(sin x);(cos x)

(31 of 95) Patterns: Variation - Introduction

More general patterns may be observed by comparing successive items produced in applying a function to a systematic list argument.

Items may be compared in various ways, notably by subtraction and by division.


In [ ]:
] x=:i. 8        NB. The identity function ] displays x

In [ ]:
] y=: x ^ 2

In [ ]:
] z=: 2 ^ x

In [ ]:
}. y             NB. Drop first of y

In [ ]:
}: y             NB. Drop last of y

In [ ]:
(}. y) - (}: y)  NB. Subtraction of adjacent items of y

In [ ]:
(}. z) % (}: z)  NB. Ratio of adjacent items of z

(32 of 95) Differences and ratios

We now define functions called dif and rat to perform these comparisons.


In [ ]:
dif=: }. - }:

In [ ]:
rat=: }. % }:

In [ ]:
dif y

In [ ]:
dif dif y

In [ ]:
rat z

In [ ]:
rat rat z

In [ ]:
dif rat z

In [ ]:
c=:x*x*x  NB. cube

In [ ]:
dif c

In [ ]:
dif dif c

In [ ]:
dif dif dif c

(33 of 95) Differences and ratios (ctd)

f ^: n is "f to the power n", that is, n applications of the function f.


In [ ]:
q=:x*x*x*x*x

In [ ]:
q

In [ ]:
dif dif q

In [ ]:
dif ^:2 q

In [ ]:
dif ^: 0 1 2 3 4 5 6 q

(34 of 95) Series - Introduction

In the list a=: 1 3 5 7 9 11, the expression 2{a selects the item with the value 5, and 2 is said to be its "index".

The function f=: >:@+: gives each element of a as a function of its index, and is said to define the "series" a. This is true only for arguments in the list i.#a, but if we assume (or assert) that f applies to every index, then it is said to define an "infinite" series.


In [ ]:
a=: 1 3 5 7 9 11

In [ ]:
2{a

In [ ]:
7{a

In [ ]:
f=:>:@+:  NB. >: is increment, and +: is double

In [ ]:
f 2

In [ ]:
f 7

In [ ]:
f i.20

(35 of 95) Determining a defining function

Using the list b=: 0 _2 _4 0 16 50 108 we can define a function for the corresponding series. We will use repeated application of the difference function dif=:}.-}: to obtain the coefficients for the falling factorial polynomial ffp=:p.!._1. These matters will be discussed more fully in a subsequent chapter on polynomials.


In [ ]:
b=:0 _2 _4 0 16 50 108

In [ ]:
dif=:}.-}:

In [ ]:
dif^:0 1 2 3 4 b

In [ ]:
c=:0 _2 0 6 0       NB. First column of table of differences

In [ ]:
]ncoeff=: c % !i.#c NB. Normalized coefficients

In [ ]:
ffp=:p.!._1         NB. Falling factorial polynomial

In [ ]:
ncoeff ffp i.7      NB. Reproduces b

In [ ]:
f=: ncoeff&ffp      NB. A function that defines (and extends) the series

In [ ]:
f i. 15

(36 of 95) Determining a defining function (ctd)

Try further examples, as illustrated below.


In [ ]:
b=: 3+(i.7)^5

In [ ]:
b

In [ ]:
dif^:(i.7) b

In [ ]:
c=: {."1 dif^:(i.7) b

In [ ]:
c

In [ ]:
(c%!i.#c) ffp i.10

(37 of 95) Polynomials - Introduction

The expression 2*x^3 is a monomial (single name), and a sum of monomials is a polynomial.

The expression c p. x is a polynomial with "coefficients" c.


In [ ]:
x=:5

In [ ]:
x^3

In [ ]:
2*x^3

In [ ]:
x=:0 1 2 3 4 5

In [ ]:
2*x^3

In [ ]:
c=:3 1 4 2

In [ ]:
c p. x

In [ ]:
(3*x^0)+(1*x^1)+(4*x^2)+(2*x^3)

(38 of 95) Polynomials - Introduction (ctd)

Polynomials are important for a number of reasons:

  1. A sum of polynomials is a polynomial
  2. A product of polynomials is a polynomial
  3. The derivative of a polynomial is a polynomial
  4. The integral of a polynomial is a polynomial
  5. Polynomials serve to approximate many functions, such as sine, cosine, and exponential.

In [ ]:
c=:1 3 3 1

In [ ]:
d=:4 3 2 1

In [ ]:
e=:1 2 1

In [ ]:
(c p. x)+(d p. x)

In [ ]:
(c+d) p. x

In [ ]:
(c p. x)*(e p. x)

In [ ]:
1 5 10 10 5 1 p. x

In [ ]:
(1%!i.10) p. x

In [ ]:
^ x

(39 of 95) Sums and products

Since (e,0) p. x is equivalent to e p. x, coefficients that differ in number of items can be added as illustrated below.

Moreover, the coefficients of a product can be obtained from the multiplication table by using the adverb /. to sum its diagonals.


In [ ]:
c+(e,0)

In [ ]:
((e,0) p. x) = (e p. x)

In [ ]:
c */ e

In [ ]:
</. c */ e   NB. Box diagonals

In [ ]:
+//. c */ e  NB. Sum diagonals

In [ ]:
(1 5 10 10 5 1 p. x) = ((c p. x) * (e p. x))

(40 of 95) Derivatives and Integrals

The derivative of a polynomial is obtained by multiplying each monomial by its exponent, and reducing the exponent by 1.

Equivalently, the coefficients of the derivative of c p. x are obtained by multiplying c by the exponents i.#c, and dropping the first item.


In [ ]:
c

In [ ]:
i.#c

In [ ]:
c * i. # c

In [ ]:
der=:}. c * i. # c NB. Coefficients of derivative

In [ ]:
der

In [ ]:
require 'plot'

In [ ]:
PLOT=:'stick,line'&plot

In [ ]:
PLOT x;>(c p. x);(der p. x)

(41 of 95) Derivatives and Integrals (ctd)

Conversely, the coefficients of the integral of c p. x are obtained by dividing c by 1+i.#c, and appending a leading constant of integration (for which we will use 20).


In [ ]:
c

In [ ]:
1+i.#c

In [ ]:
c % 1+i.#c

In [ ]:
int=: 20 , c % 1+i.#c

In [ ]:
int

In [ ]:
PLOT x;>(c p. x);(int p. x)

(42 of 95) Derivatives and Integrals (ctd)

We now define functions DER and INT for the derivative and integration of coefficients.


In [ ]:
DER=:}.@(]*i.@#)

In [ ]:
INT=:[,(] % >:@i.@#@]) NB. >: is the "increment" function

In [ ]:
DER c

In [ ]:
20 INT c

In [ ]:
DER 20 INT c

(43 of 95) Derivatives and Integrals (ctd)

If ce is a list of coefficients that approximates the exponential, then DER ce is approximately equal to ce.


In [ ]:
ce=:1 % ! i. 7

In [ ]:
ce

In [ ]:
ce p. 0 1 2 3 4

In [ ]:
^ 0 1 2 3 4

In [ ]:
DER ce

In [ ]:
DER DER ce

In [ ]:
1 INT ce

(44 of 95) Falling Factorial

The falling factorial function is related to the power function, obtained as a "variant" of it by using ^ !. _1.

The falling factorial polynomial ffp=: p. !. _1 (used in the chapter on series) is a polynomial based on the falling factorial rather than the power.


In [ ]:
x=:5

In [ ]:
e=:4

In [ ]:
x^e

In [ ]:
x*x*x*x

In [ ]:
ff=: ^!._1  NB. Falling factorial function

In [ ]:
x ff e

In [ ]:
(x-0)*(x-1)*(x-2)*(x-3)

In [ ]:
*/(x-i.e)

(45 of 95) Taylor Series - Introduction

A series that can be used as coefficients of a polynomial to approximate a function f is called the Taylor series for f. Taylor series are provided by the adverb t. as illustrated below.


In [ ]:
^ t. 0  NB. Leading item of Taylor series for the exponential

In [ ]:
^ t.i.7 NB. First seven items of TS for ^

In [ ]:
sin=: 1&o.

In [ ]:
cos=: 2&o.

In [ ]:
sin t. i.7

In [ ]:
cos t. i.7

In [ ]:
i:3

In [ ]:
(cos t. i.7) p. i:3

In [ ]:
cos i:3

(46 of 95) Extended Precision and Rationals

The expression ! x: 20 gives factorial 20 to complete precision. Moreover, 2 % x:3 gives the result of dividing 2 by 3 in rational form.


In [ ]:
! 20             NB. Approximation in "scientific notation"

In [ ]:
! x: 20

In [ ]:
2%3

In [ ]:
2%x: 3

In [ ]:
]a=:% 1 + i. x:6  NB. Reciprocals in rational form

In [ ]:
a +/ a            NB. Addition table

(47 of 95) Extended Precision and Rationals (ctd)


In [ ]:
a

In [ ]:
a */ a

In [ ]:
a %/ a

In [ ]:
^ t. i. x: 10 NB. Taylor series in rational form

(48 of 95) Joint display

A joint display of Taylor series.


In [ ]:
>((^t.);(sin t.);(cos t.)) i. x:10

(49 of 95) Binomial Coefficients - Introduction

Matrix products and inverses of binomial coefficient tables give interesting results.


In [ ]:
]bct=: (i.7) !/ (i.7)

In [ ]:
]abct=: %. bct NB. Inverse gives alternating binomial coefficients

In [ ]:
+/bct          NB. Column sums

In [ ]:
2^i.7

In [ ]:
+/abct         NB. Not all zeros

(50 of 95) Matrix Products of bct


In [ ]:
mp=: +/ . * NB. Matrix product function

In [ ]:
bct mp abct

In [ ]:
bct mp bct

In [ ]:
bct mp bct mp bct

(51 of 95) Identities

Since the matrix products of abc are sums of products of binomial coefficients, any independent expression that gives these "powers" of bct yields a host of identities concerning binomial coefficients.


In [ ]:
bct4=:bct mp bct mp bct mp bct

In [ ]:
bct4       NB. What is the developing pattern?

In [ ]:
bct4 % bct NB. pattern clarified by element-by-element division

(52 of 95) Identities (ctd)

We can now use a subtraction table as an exponent to give a result equal to bct4 (the fourth "power" of bct).


In [ ]:
]st=: - (i.7) -/ (x: i.7)

In [ ]:
4 ^ st

In [ ]:
bct * 4 ^ st NB. Enter bct4 to compare with this result

(53 of 95) Geometry - Tables of coordinates

A 4-by-3 table can be used to represent coordinates of the 4 vertices of a tetrahedron in 3-space, and an n-by-2 table represents the n vertices of a polygon.


In [ ]:
]tri=:>0 0;7 4;3 0 NB. Base length 3 and altitude 4

In [ ]:
tri,.0.5           NB. Border with column of halves

In [ ]:
det=:-/ . *        NB. Determinant function

In [ ]:
det tri,.0.5       NB. Signed area (<0 vertices in clockwise order)

In [ ]:
area=: det@(,.&0.5)NB. Define area function

In [ ]:
area tri

(54 of 95) Area of triangle

Analysis of this use of the determinant for triangles (and tetrahedrons) may be found in Klein "Elementary Mathematics From an Advanced Viewpoint".

Because areas of triangles are signed, the area of any polygon can be obtained by adding lines to triangulate it, and summing the areas.


In [ ]:
]cctri=:0 2 1{tri NB. Counterclockwise triangle

In [ ]:
area cctri

(55 of 95) Regular pentagon

A regular pentagon is obtained by appying the cos and sin to angles at intervals of 2r5p1 (two-fifths of pi), and displayed by applying plot to the boxed x and y coordinates.


In [ ]:
cos=:2&o.

In [ ]:
sin=:1&o.

In [ ]:
]pent=:(cos,.sin) 2r5p1 * i. 5

In [ ]:
require 'plot'

In [ ]:
|:pent    NB. Transpose table

In [ ]:
;/|: pent NB. Box rows (columns of pent)

In [ ]:
(fix=: ;/@|:) pent

In [ ]:
plot fix pent

(56 of 95) Regular pentagon (ctd)

The missing line from the last vertex to the first can be provided as follows.


In [ ]:
0 1 2 3 4 0{pent

In [ ]:
plot fix 0 1 2 3 4 0{pent

(57 of 95) Improper polygon

An interchange of indices 1 and 2 illustrates the possibility of an"improper polygon" whose sides cross.


In [ ]:
0 2 1 3 4 0{pent

In [ ]:
plot fix 0 2 1 3 4 0{pent

(58 of 95) Triangulation

The pentagon may be triangulated as follows:


In [ ]:
plot fix 0 1 2 3 4 0 2 0 3 0 4{pent

(59 of 95) Area of pentagon

These triangulated components of the pentagon can be selected and boxed, and their areas can be determined, as follows:


In [ ]:
]bt=: (0 1 2{pent);(0 2 3{pent);(0 3 4{pent)

In [ ]:
area&> bt

In [ ]:
+/ area&> bt NB. Total area of pentagon

(60 of 95) Area of concave pentagon

Although the function area gives signed results according to the clockwise or counter-clockwise order of the vertices, these areas are all of the same sign.

This occurs because pent is a convex polygon, and the significance of signed areas is not apparent. We will make it so by using a concave polygon, obtained by multiplying the second vertex of pent by zero.


In [ ]:
]concave=: 1 0 1 1 1*pent

In [ ]:
plot fix 0 1 2 3 4 0{concave

(61 of 95) Area of concave pentagon (ctd)

The boxed coordinates of the triangular components of the concave pentagon are obtained as shown below. Their areas are not all of the same sign, but sum to give its total area.


In [ ]:
]btc=: (0 1 2{concave);(0 2 3{concave);(0 3 4{concave)

In [ ]:
area&> btc

In [ ]:
+/area&> btc

(62 of 95) Displacement and side length

The displacement from one vertex to the next can be obtained by rotating the table of vertices up by one place, and subtracting from it the original table.


In [ ]:
tri

In [ ]:
1 |. tri

In [ ]:
(1 |. tri)-tri

In [ ]:
disp=: 1&|. - ]

In [ ]:
disp tri

(63 of 95) Displacement and side length (ctd)

The lengths of the sides can then be obtained from these displacements as the square root of the sum of the squares.


In [ ]:
length=: %:@(+/)@(]*])"1

In [ ]:
]sides=:length disp tri

(64 of 95) Heron's formula

Heron's formula for the (unsigned) area of a triangle is the square root of the product of the semiperimeter with the semiperimeter less each of the sides.


In [ ]:
sp=: %&2 @ (+/)

In [ ]:
sp sides

In [ ]:
(sp , sp - ]) sides

In [ ]:
*/ (sp , sp - ]) sides

In [ ]:
%: */(sp , sp - ]) sides

In [ ]:
area tri NB. Compare with signed area

In [ ]:
Heron=: %: @ (*/) @ (sp , sp - ])

In [ ]:
Heron sides

(65 of 95) Slope and Rate of Change - Introduction

The rate of change of a function is an important attribute: for example, the rate of change of the sine is the cosine, the rate of change of the exponential is itself, and the rate of change of the nth power is n times the (n-1)th power.

Although the instantaneous rate of change at a point may be difficult to determine, the average rate of change over a non-zero interval i is straightforward.


In [ ]:
f=: 3:*]*]        NB. three times the square

In [ ]:
x=:0 1 2 3 4 5

In [ ]:
i=:0.1

In [ ]:
f x

In [ ]:
f x+i

In [ ]:
(f x+i)-(f x)     NB. Rise over interval

In [ ]:
((f x+i)-(f x))%i NB. Average rate of change

(66 of 95) Slope

We use the term "slope" for the average rate of change, because the graph of a function at intervals of i exhibits the average rate of change as the slopes of the lines connecting successive points.


In [ ]:
require'plot'

In [ ]:
PLOT=:'stick,line'&plot

In [ ]:
i*i.20

In [ ]:
f i*i.20

In [ ]:
PLOT f i*i.20

(67 of 95) Slope (ctd)

For a small interval the average slope approaches the slope AT each point, a result that is called the derivative of the function.


In [ ]:
smi=:0.001

In [ ]:
PLOT f smi*i.100

(68 of 95) Slope (ctd)

The derivative (the slope AT a point) should be given by a zero interval, but this is the meaningless division of a zero rise by a zero interval.

However, the case of a power function can be analyzed to give a simple meaningful result. For example, the cube function applied to x+i gives

```(x*x*x)+(3*x*x*i)+(3*x*i*i)+(i*i*i)```

```Sutraction of the cube of x gives:```

```(3*x*x*i)+(3*x*i*i)+(i*i*i)```

```which can be divided by i to yield:```

```(3*x*x)+(3*x*i)+(i*i)```

```Since i is zero, the last two terms can be dropped to yield```
```3*x*x (that is, three x squared, or formally, 3:*]*]) for the slope with zero interval.```

(69 of 95) Slope (ctd)

Similar analysis for other powers gives n*x^(n-1) as the derivative of x^n Moreover, the derivative of a multiple of a function is the same multiple of the derivative, and the derivative of a sum of functions is the sum of their derivatives.

These observations extend the analysis to polynomials, with the simple consequence that the derivative of the polynomial c&p. is the polynomial d&p., where d=:}. c*i.#c.


In [ ]:
]c=:1&o. t. i. x:8 NB. Taylor series for sin

In [ ]:
c*i.#c

In [ ]:
]d=:}.c*i.#c       NB. Coefficients for derivative (cos)

In [ ]:
d&p. y=:0.1*i:30   NB. Range from about -pi to pi

In [ ]:
PLOT y;>(c&p. y);(d&p. y)

(70 of 95) Slope (ctd)

The foregoing shows that the essential notion of the calculus (that is, the derivative) can be treated without resort to the general analysis of limits, provided that attention is restricted to polynomials or to rational functions obtained as the ratio of polynomials.

Since polynomials and rationals can be used to approximate all the functions of interest in an introductory course in calculus, this is not a serious restriction. This approach to the calculus will be pursued in the next chapter.

(71 of 95) Calculus - Introduction

We will restrict attention to polynomials, and will use the results developed in the chapter on Slopes.


In [ ]:
DER=: }. @ (] * i.@#)     NB. Gives coefficients of derivative

In [ ]:
INT=: [ , (] % >:@i.@#@]) NB. Gives coefficients of integral

In [ ]:
c=: 1 3 3 1

In [ ]:
DER c

In [ ]:
4 INT c                   NB. Constant of integration 4

In [ ]:
DER 4 INT c

In [ ]:
(DER c) p. x=:i.7         NB. Evaluation of derivative polynomial

In [ ]:
c&p. d.1 x                NB. First derivative of c&p.

(72 of 95) Calculus - Introduction (ctd)

The operator d. gives successive derivatives of various orders (using d.1 and d.2 and d.3, etc.), as well as integrals (using d._1 d._2 etc.).


In [ ]:
c&p. x

In [ ]:
c&p. d.1 x

In [ ]:
c&p. d.2 x

In [ ]:
c&p. d._1 x

In [ ]:
c&p. d._2 x

In [ ]:
c&p. d._1 d._1 x

In [ ]:
c&p. d._1 d.1 x

(73 of 95) Calculus - Introduction (ctd)

The Taylor adverb t. gives the coefficients of derivatives and integrals.

From the results shown below it is clear that d._1 uses a zero constant of integration. The effect of any other can be obtained by adding it.


In [ ]:
c&p. d.1 t. i.7

In [ ]:
c&p. d.2 t. i.7

In [ ]:
c&p. d._1 t. i.7

In [ ]:
(4: + c&p. d._1) t. i.7

(74 of 95) Theorems and proofs - Theorems

A theorem is an assertion that one expression L,the left limb, is equivalent to another R, and may be expressed as the function T=. L -: R . A theorem may also be called a tautology, a function that yields 1 (true) for any argument. For example:


In [ ]:
L=: +/@i.             NB. Sum of integers

In [ ]:
R=: (] * ] - 1:) % 2:

In [ ]:
T=: L -: R

In [ ]:
(T ; L ; R ; i.) 6

(75 of 95) Theorems and proofs - Theorems (ctd)

We can also assign the name n to the right argument function ] to allow a function such as R1 to be written more readably for a beginner. Thus:


In [ ]:
n=: ]

In [ ]:
R=: (n*n-1:)%2:

In [ ]:
R 6

(76 of 95) Proofs

A proof is a sequence of equivalent expressions that lead in justifiable steps from a left limb to a right. We will write one expression below another to assert that it is equivalent to the one above it, possibly annotating it with the justification to provide a formal proof:

```L NB. Theorem 1```

```+/@i. NB. Definition of L```

(77 of 95) Proofs (ctd)

The foregoing proof can be illuminated by entering each expression followed by an argument, and observing that each gives the same result. Any mis-step in a proof will likely show an anomolous result.

An expression can be conveniently entered by moving the cursor up to it, pressing enter to bring it to the input area, modifying it by inserting the argument, and then pressing enter. Moreover, partial expressions may be entered to observe their results. Thus:


In [ ]:
L 6

In [ ]:
+/@i. 6

In [ ]:
+/@|.@i.6 NB. Sum is associative  and commutative (|. reverses)

In [ ]:
(((+/@i.)+(+/@|.@i.)) % 2:)6  NB. Half sum of equal quantities

In [ ]:
R 6

In [ ]:
(i. + |.@i.) 6 NB. To show that this is indeed a list of n-1

(78 of 95) Proofs (ctd)

How would you express the second step (+/@|.@i.6) in conventional notation (without English or arm-waving). Remember that Sigma from 5 to 0 is a sum over an empty list)

Reproduce other of the proofs in pure conventional notation.

(79 of 95) Proofs (ctd)

The following is a similar proof that the sum of the first n odd integers equals the square of n:

```(odds=: 1: + 2: \* i.) NB. First odd integers```

```+/@(1: + 2: \* i.) NB. Sum of odds```

```(n + +/@(2: \* i.)) NB. Sum of n ones is n```

```(n + 2: \* +/@i.) NB. Sum of twice is twice sum```

```(n + 2: \* (n \* n - 1:) % 2:) NB. Result of preceding theorem```

```(n + n \* n - 1:) NB. Simple algebra```

```(n \* n) NB. Simple algebra```

```*: NB. Definition of square```

(80 of 95) Induction

An inductive proof is based (explicitly or implicitly) on a recursive definition of a function. Recursive definition is treated in the next chapter.

(81 of 95) Selcting topics

This is the end of this chapter. To continue with the next chapter, advance as usual. But to select any other chapter, click on Chapters under the Studio menu.

(82 of 95) Recursion - Introduction

If a function recurs in the expression that defines it, the function is said to be recursively defined. Such a definition must be supplemented by a definition for some specific argument, using an expression that does not make use of the function being defined.

For example, the factorial of the argument j may be defined by j * f j-1 (or more formally by ] * f@<:), supplemented by the definition 1: (the constant function 1) for the case j=: 0. Thus:


In [ ]:
f=: 1:`(]*f@<:) @. *

In [ ]:
f 5

In [ ]:
f"0 i. 6 NB. The function f is applied to each rank-0 cell

(83 of 95) Recursion - Introduction (ctd)

In the foregoing definition, the signum function * yields 0 if the argument is zero, and 1 if it is greater than zero.

Consequently, the agenda @. chooses the last element of the gerund 1:`(]*f@<:) each time until the argument (repeatedly decremented by <:) becomes zero, in which case it chooses the constant function 1:, thus terminating the process.

Alternatively, the imposition of zero rank could be incorporated in the recursive definition:


In [ ]:
f=: 1:`(]*f@<:) @. * " 0

In [ ]:
f i. 6

(84 of 95) Recursion - Introduction (ctd)

The reference to f within the definition works only because the name f is assigned to the function defined; we may instead use the symbol $: for self-reference to define an anonymous function to which any name may be assigned:


In [ ]:
1:`(]*$:@<:) @. * " 0 i. 6

In [ ]:
factorial=: 1:`(]*$:@<:) @. * " 0

In [ ]:
factorial i. 6

(85 of 95) Quicksort

Quicksort is an interesting example of the use of recursion: the basic procedure is the segregation of the items of an argument list according to whether they are less than the leading item, equal to it, or greater than it.

This procedure is applied recursively to the segregated lists, repeating as long as the argument has more than one item.


In [ ]:
y=: 52 9 65 41 70 91 52 76 26 4 73 32 63

In [ ]:
less=:    ([ < {.) # ]

In [ ]:
equal=:   ([ = {.) # ]

In [ ]:
greater=: ([ > {.) # ]

In [ ]:
less y

In [ ]:
(less;equal;greater) y

In [ ]:
qs=: ]`($:@less, equal, $:@greater) @. (# > 1:)

In [ ]:
qs y

(86 of 95) Quicksort (ctd)

Details of the action of the recursive definition of quicksort can be analyzed as illustrated below.


In [ ]:
seg=: less;equal;greater

In [ ]:
y

In [ ]:
seg y

In [ ]:
> {. seg y       NB. Select and open first (less-than)box

In [ ]:
seg > {. seg y   NB. Segregate "less-than" list

In [ ]:
; seg > {. seg y NB. Raze the boxed list

In [ ]:
> {: seg y       NB. Select and open last (greater-than) list

In [ ]:
seg > {: seg y

(87 of 95) Quicksort (ctd)

Continuation may lead to empty boxes.


In [ ]:
seg y

In [ ]:
> {. seg y

In [ ]:
seg > {. seg y

In [ ]:
> {. seg > {. seg y

In [ ]:
seg > {. seg > {. seg y

In [ ]:
; seg > {. seg > {. seg y

(88 of 95) Permutations and Anagrams - Introduction

A permutation (re-ordering) of the letters of a word is called an anagram, and may be performed by the anagram function denoted by A. -- an anagram may or may not be an English word.


In [ ]:
w=:'ART'

In [ ]:
2 A. w

In [ ]:
4 A. w

In [ ]:
!# w  NB. The number of anagrams (permutations) of w

In [ ]:
i.!#w NB. The indices of all !3 anagrams of w

In [ ]:
(i.!#w) A. w

(89 of 95) Permutations and Anagrams - Introduction (ctd)

The list to be permuted may be numbers, and the result may be used to index any list of the correct number of items.


In [ ]:
]top=: (i.6)A.0 1 2 NB. Table of permutations

In [ ]:
top { 'ART'

(90 of 95) Permutations and Anagrams - Introduction (ctd)

The right argument may be any list of items, such as a boxed list of words.


In [ ]:
]boxedlist=:'zero';'one';'two'

In [ ]:
top{boxedlist

(91 of 95) Permutations and Anagrams - Introduction (ctd)

This indexed list can also be produced by direct use of A. and the two equivalent results will be displayed side-by-side (separated by a boxed empty list provided by a:).


In [ ]:
(top { boxedlist) ,. a: ,. ((i.6) A. boxedlist)

(92 of 95) Permutations and Anagrams - Introduction (ctd)

(i.!4) A. 0 1 2 3 (or (i.!4) A. 'ABCD') produces a complete permutation table of order 4. Coloring this table gives a pattern that "shows why" there are 432*1 (that is, !4) permutations of order 4.

The color window is better if expanded (by clicking in the middle tiny square at upper right of the window).


In [ ]:
require 'viewmat'

In [ ]:
color=:viewmat

In [ ]:
color (i.!4) A. 'ABCD'

(93 of 95) Permutations and Anagrams - Introduction (ctd)

A list (such as p=: 3 0 4 1 2 5) that is a permutation of its indices is called a permutation vector, and p&{ is the corresponding permutation function.

This permutation can also be prescribed by stating that position 3 receives the item from position 1, that that position receives from position 0, and that (completing the cycle) receives from position 3; further that position 4 receives from 2, which receives from 4; and position 5 (a cycle of one) remains in place.

A boxed list of this cycle representation is given by the function C. .


In [ ]:
p=: 3 0 4 1 2 5

In [ ]:
p&{ 'ABCDEF'

In [ ]:
C. p

In [ ]:
(C. p)&C. 'ABCDEF'

(94 of 95) Permutations and Anagrams - Introduction (ctd)

We now box each row of the table p4 of permutations of order 4, append to the result the cycle representations of p4, and transpose the whole for easier reading. Only the first 10 values are shown.


In [ ]:
10 {. p4=: (i.!4) A. i.4

In [ ]:
|: 10 {. (<"1 p4=: (i.!4) A. i.4) ,. (C. p4)

(95 of 95) Permutations and Anagrams - Introduction (ctd)

This is the end of the lab.

End of Lab


In [ ]: