Ex 10.2

advertisement
1. Using NotebookPut, create a notebook with one Title cell, one Section cell, one
Text cell and two Input cells.
2. Use NotebookGet to read the notebook you created in Exercise I into the kernel.
Then programmatically change the Section cells to Subsection cells either using
Cases or an appropriate rule.
). Take either of the notebooks you created in the above exercises and use Selection'.
Move and SelectionEvaluate to evaluate all of the Input cells in the notebook.
I. Using NotebookPut, create a notebook with several Text cells each containing a
ValueBox such as $version, $OperatingSystem, and $UserName.
2. Using Notebookl?ut, create a notebook with an Input cell containing the integral
1;" dI;x;. Then evaluate the integral using SelectionMove and SelectionEval '.,
uate.
J
1. Modify ShowTable so that it can display a user-specified heading in the first HJW of the
grid. Include formatting to serthe stylc of the strings in the heading to be di fferent than
th.e rest of the elemems displayed by ShowTahle.
2. Modify ShowTable so that it automatically partitions the list it is passed to be
rectangular, vr.1th the number of rows and cohnnns as close to each other as possible.
3. Create a function TruthTable [expr, vm,] that displays the logical expression e;'1>1"
together vr.1th all the possible truth values for the variables in the list vars. For example,
here is the truth table for the expresSion (A V B) => C.
In[1]:. TruthTable[Implies [A
liB,
C], {A, B, C}]
OU1{l)1/DisplayForllF
A
(AVB) -> C
C
,
,
,,,
,
,, ,
,, ,
,, ,
,, ,
,, ,
,,,
T
,
,
,
,
,
,
,
,
You will first need to create a list of all possible troth value assignments for the
variables, A, B, C in this case. One approach would be to use Distribute. $0,
essentially, this is the left-hand side, or first three columns of the above table (not
counting the first row containing the table headings).
In{2J:_ va.rs"
IA. B, C};
len" Length[va.rs]; ins"
Distdbute [Table [{True. False}, {len}], List, List, List]
OUl{3p {{True,
True, True), {True, 'l'rue, False}, {True, False, True}, {True, False,
False], {False, Tr--.!e, True}, {False, True, False}, {False, False, 'l'rue] ,
{False, False, False}}
You can then create a list of rules associating e~ch of these triples of troth values vr.1th
~ triple of variables.
lnf4J.''' Map[Thread[vara ..• #l]
&,
ins]
0111[4p ({A-->True, B ..• True, C-->True).
{A-->True, B ..• True, C-->False}, {A ..• True, B ..• False, C-->True},
{A-->True, B ..• False, C ..• False}, {A-->False, B ..• True, C--> True} ,
(A-->False, B ..• 1'rue, C-->False}, {A-->False, B ..• False, C-, True} ,
{A-->False, B-->False, C-->Falsej}
Substituting these rules into the logical expression produces a truth value for e~ch of the
above rows.
Inf5J:~ Impliea[A
liB, C] /. Map[Thread{vara
--> #1] &. in •• ]
Ou/[Sp {True, False, True, False, True, False, True, True}
Your task is ro put all these pieces together in a GridBox ,,~th appropriate
formatting.
1. Create a button that will serve as a template fot the Plot 3D function.
2. Create a button that will wrap Expand [] atound any selected exptession and
evaluate that expression.
3. Using GridBox, create a palette of buttons that operate on poiynomials like that in
Exercise 2. Include in your palette a button for each of Expand, Factor,Apart, and
Together.
1. Create a function ReadSolarData [file, opts] that reads in a solar data file such as
23232.txtusing ReadList, strips out any line beginning with a quote character, and
returns the remaining lines with each element converted to a number. You should set
explicit options to ReadSolarData that borrow from ReadList.
2. Create a function th:!t computes the total solar radiation for ~ given year from
one collector (your choice) from tho; data file 23232.o:t. Make a plot comparing
these yearly radiation values for the history of the dataset.
3. Create a function PlotSolarData [dtlt1 ,dat2 , opts] that uses MultipleList ", Plot as in
the previous section to plotdatasets dati and dati. Your function should include
customized tick infurmatiun, axes labels, and a legend that displays the latitude
and longitude of the collector in the LegendLabeL In addition, you function should
be able to accept options similar to MultipleListPlot and pass them directly to Mul
tipleListPlot.
4. Overload PlotSolarData so that when o;valuated as Plot Solan
Data [mollth. opts] , and month is olle of)anumy, Febru~ry, ... , December, it will
produce a plot comparing the solar radiation for that month across all years of the
dataset.
1. The version of Random Walk developed in this section generates one-dimensional
walks of unit step. Modify RandomWalk so that the step size is a unifonnly distributed
random number between -1 and 1.
2. Modify ShowWalk so that it produces a ListPlot when passed something ofthc form
RandomWalk [n, DimensioD-c'l].
3. The RandomWalk program developed in tlJis section is not set up properly to take unit
steps in three dimensions on the off-lattice walk. The following fommlas can be used to
represent a point parametrically on the unit sphere.
x(¢,B)=cos(B)Vl-cos2(¢l y(¢,
(l)=sin«(l)V1-cosZ(t/Jj
z(¢)=cos(¢)
Use these formulas to rewrite walk3DOffLattice so that off-lattice three-dimensionalwalkstakeunitsteps.
4. The square end-To-end distance of a two-dimensional walk is defined as
(Xi -xd
+ (Yf - Jil', where (Xi,Yi) and IXf, Yf) are the initial and fmallocations of the walk,
respectively. Assuming the initial point is the origin, then this simplifies to
xl +
y}.
Write a function SquareDistance that takes a two-dimensional walk as an
argument and computes the square end-to-end distance. Write a usage message and
include this function as a publicly exported function in the Random Walks,rn package.
S. Create a funcuonAnimateWalk tlIat takes RandomWalk [11, Dim"nsion-c'2] as an
argument and produces a series of graphics that can be animato;d by di~'Playing in
quick succession. Include in your graphics a red disk that mOVe5 to the "<.-urrent
position" in the walk. TIle viewer will then see this red disk moving along on tho;
random walk as tile animation is played.
6. Modify AnimateWalk from the previous exercise so that it can also accept the
output from RandomWalk [n, Dimension-c'3].
1. Define a new graphics function LifeGraphics that creates a raster array of color
values. Setitup so that it takes an option Colors defined to have default values for 1 and
0 and such that you can give it your own coloring scheme. Then you will display Life
games with Show [LifeGraphics [LifeGame [" , steps] ]].
2. The Game of Life is most interesting to watch when persistent patterns, known a~
life-forms, occur during the evolution process. One patteru that ha~ been e){ten~ively
studied is known as the glider, which b defined by
glider[x_, Y_l ,.
{{x, y}, {x+l, y}, {x+2, yj, {x+2, y+l}, {x+l, y+2}}
Modify the program for the Game of Life so that tbe lattice can be seeded with life forms
and observe the behavior ofa glider (it should appear, disappear, and then reappear in a
shifted position every fifth generation). To better understand the use of the periodic
boundary conditions, note what happens when a glider pattern moves beyond a border of
the game board.
1. This series of exercises will walk you through the creation of a package Collatz.
m, a package of functions for performing various operations relat",,j to the ColJau
problem that we investigated earlier (Exercise 5 of Section 5.3, Exercises 6 and 7
of Section 6.2, and Exercise 3 of Seetion 7.6). Reeall that the CoHau function, fix
T
any integer n, rerurns 3 n + 1 for odd n, and for even >I. The (as yet unproven)
CoJlat~ Conjecture is the statement that, for any initial positive integer n, the
iterates of the Collatz function always reach the cycle 4, 2, 1, .... Start by creating
an auxiliary function collatz [n] that returns 3 n + 1 for n odd andnf2 forn even.
2. Create the function CollatzSeqmmce [n] that returns a list of the iterates of the
auxiliary funetion collatz [n] from the previous exercise. Here is some sample
output of the CollatzSequence function.
In{l}'~
C011atzSeguence[7]
OUl{IJ- {7,22,ll,34,17,52,26,13,40,20,10,5,16,a,4,2,1}
1n{2].~
Co11atzSeguen"e[lll]
Ou!(2)~
[111, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425,
1276,638,319,958,479,1438,719,2158,1079,3238,
1619,4858,2429,7268,3644,1822,911,2734,1367,4102,
2051,6154,3077,9232,4616,2308,1154,577,1732,866,
433,1300,650,325,5'76,488,244,l22,61,184,S2,46,
~3, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1}
3. Create a usage message for CollatzSequence and warning messages for each of
the following situations.
{J.. notint: the argument to CollatzSequence is not a positive integer
h. argx: CollatzSequence was called with the Wl'ongnumbel" ofaq,'umems
4. l\Iodify the definition of CollatzSequence that you created in Exercise 2 above so
that it does some error trapping and issues the appropriate warning message that
you created in Exercise 3.
5. Finally, put all the pieces together and write a package CollatzSequence. m that
includes the appropriate Beginpackage and Begin &"tatements, usage messages,
warning messages, and function definitions. Put your package in a directory where
Mothematica can find it on its search path and then test it to see that it returns
correct output such as the examples below.
/n)lJ:~
« IPM3'Collatz'
/n[2J:~ ?CollatzSequence
CollatzSequence[n] computes the sequence of
Collatz iterates starting with initial value n. The sequence
terminates as seen as it •. eachE" the valUE 1.
mPF~ CellatzSBquBncB[37]
0"1[31= {37,112,56,2B,14,7,22,11,
34,
17,52,26,13,40,20,lO,S,16,B,4,2,l}
ReTe are various cases in which CollatzScquence is given bad input.
1~4F~
Collat2Sequen"e[_5]
CollatzSequence: :notint : First a;J:"gument, -5,
to CellatzSequence must be a positiv<= integer.
1n)5F~ Co11atzSequen"e[4, 6]
CollatzSequence:,arg~
CollatzSequence cal1<=d with 2 arguments; 1
argument is <=xpected. More ...
OUI[5J- CollatzSequence[4, 6]
d. randLis4[n]
= Table [Random[], {n}]
2. Consider the two functions f and g, which are identical except that one is "Written
using an immediate assignment and the other using a de1ay",d assignment.
In(lJ;~ f[n_l
= Slmll(l+x)J, {j, 1, n}]
(l+x) (-1 + (l+x)")
Out[l1=
In{2l~ g[n_] :=SIml[(l+x)J, {j, 1, n}]
Explain why the output of th",se two functions rook so different. Are they in fact
different?
I,,{S]::
Oul(al
~
£[2]
(l+x)
(-1+ (1+X)2)
x
In{4J:~
g[2]
Out[4
~
l+x+
(l·'x)"
3. Create a piecewise-defined function g{x) based on the following and then plot the
functionfrom-l toO.
-~I-(X+2i g(x) =
1
~
-2s;xs;-1
1. Create a predicate function that remms a value of True ifit~ argument is between -1
and L
2. Write a predic~te function NaturalQ [n] that returns a value of True jf n is a namral
number and False otherwise; that is, NaturalQ In] is True ifn is among 0,1,2,3, ....
3. Create a predicate function SubsetQ [tisl, iis2] thatremrns a value of True if lis! is a
subset of liS!. Remember: the empty set {}, is a subset of every-set.
1. Generatethelist{{O},{O,2},{0,2,4},{O,2,4,6},{O,2,4,6,a}}in two different ways using
the Table function.
2. A table containing ten random 15 and Os can easily be created using Table [" Random
[Integer] , {10}] . Create a ten-element list of random Is, 05 and -is.
3. Create a ten-element list of random is and -Is. This table can be viewed as a list of the
steps taken in a random vi'alk along the x-axis, where a step can be taken in either the
positive x direction (corresponding to 1) or the negative x direction (corresponding to-I)
with equal likelihood.
The random walk in one, 1;\''-0, three (and even higher) dimensions is used in science and
engineering to represent phenomena that are probabilistic in narure. We will use a
variety of random walk models throughout this book to iIl11sttate specific programrningpoints.
4. From a mathematical point of view, a list can be viewed as a vector and a nested list
containing inner lists of equal length can he viewed as a matrix (or an array). Mathematico has another built-in function Array which creates lists. We can use an
undefined function f to see how Array works.
1n{1]:_
oul[ll=
In[2j:_
Array[f,51
{f[1],f[2],t[3],
Array[f,
f[4].f[5]}
{3,4}J
'J f[l, 'J, f[l, 4)),
, f[2, oj, f[2, 4]).
(f[2,1],
f[2, 'J
(£[3,1],
f[3, 'J
, f[3, 'J, £[3, 411l
, the Table function.
Generate both of these lists using
Oul[2]
=
({f[l,l],
f[l,
5 .. Predict the dimensions of the list {{ {l,a}, {4,d}}, {{2,b}, {3,c}}}. Use the Dimensions
function to check your answer.
1. Predict where the 9s are located in the following list.
{{2,1,lO},{9,S,7},{2,lO,4},{lO,1,9}.{6,1,6}}
Confion your prediction
using Position.
2. Given a list of (x, y) data points
{{Xl' YI}, {X" y,}, {X" y,}, {X4' Y4}' {X., ¥s}}
separate
the x and y components to get:
3. Consider a two-dimensional random walk on a square lattice. (Asquare lattice can
b~ envisioned as a two-dimensional grid, just like the lines on graph paper.) Each
~tep can be in one offour directions, (I, 0), {O, ll, (-I, 0), {O, -I}, corresponding to
steps in the east, north, west and south directions, respectively. Use the list
({I,O}, {O,l}, {-l,O}, {o, -1}} to create a list of the steps ofa ten-step
random walk.
't. In three steps, make a list of the elements in even-numbered locations in the list
(a,b,c,d,e,f,g}.
J. Suppose you are given a list S of length n, and a list P containingn different
numbers between I and n (that is, P is a permurntion of Range [n]). Compute the li~t
T ~uch that for all kbet\'reen 1 andn,T[ [k]]=s[[p[[k]]] ].Forexample,if
s~{a,b, c, d} and P={3, 2,4,1}, then T= {c, b, d, a}.
6. Given the lists Sand P in the previous exercise, compute the list U such that for all
k betweenlandn,U[[P[[k]]]] = s[[k]] (thatis,s[[i]] takes the value from position P
[[i] ] in U). Thus,for S={ a, b, c, d} and P~{3, 2,4, 1}, U={d,b,a,c}.
ThinkofitasmovingS [[1]] to position P[ [1]], S [[2]] to position p [[2]], and so on.
Hint: Start by pairing the elements ofp with the elementsofs.
1. How would you perform the same task as Prepend[{x,y} ,zl using the Join
function?
2. Sblrtingwith the lists {1, 2, 3,4} and {a,b, c, d}, create the list (2, 4 ,b, d).
3. Given two Jjsts, find all those elements that are not common to the two lists.
For example, sblrtingwith the lists, {a,b, c, d) and {a,b, e, f}, your answer
would returnthelist{c,d,e,f].
1. Convert the first character in a string (which you may assume ro he a lowercase
letter) to uppercase.
2. Given a string containing two digits, ,;onvert it to its integer value; so the string
"73" produces the number 73.
3. Given a string containing twO digits, convert it to its value as an integer in base 8; for
example, the string" 73" will produce the number 59.
4. Given a string of digits of arbitrary length, convert it to its integer value. (Hint: You
may find that the Dot function is helpful.)
'i. Create a Boolean function OrderedWordQ thatretums True or False depending upon
whether its argument is in alphabetic order. So OrderedWordQ ["best"] would return
True butOrderedWordQ ["brag"] would return False. Then find all those words in the
file dictionary. dat that are ordered according to this function.
Here is a platform-independent path to the dictionary file.
IniIJ:~ wordfile _ ToFileName [{ $InstallationDirectory, "Documentation",
"English", "Demos", "DataFiles"}, "diction •• :oy. dat"]
OU![lF C:\P:oogram
Files\Wolfram Research\Mathernatica\5.1\
Documentation\EngliSh\Demos\DataFiles\dictionary.dat
This reads in the file using ReadList, specifying the type of data being read in as a
Word.
in[2J:= words _ReadLietlwordfile, Word];
6. Create a function PalindrameQ lslr] that returns a value of True if its argument SIr is a
palindrome; that is, if the string str is the same forward and backward. For example,
"refer" is a palindrome.
1. Write a function addpair [{x,y}] that adds the elements in a pair. Then use your
addpair function to Sllm each pair from the following.
data" {{l, 2}, {2, 3},
p,
4}, (4, S}, {S, 6}};
Your output shonlrl look like {3,S,7,9,11}.
2. Use Apply to add the elements in each pllir from a list of pairs of numbers such as
in the previous exercise.
3. A matrix can be rotated by performing a number of successive operations. Rotate
the matrix { {:1, 2, 3} , { 4, 5, 6} } clockw;se by 90 degrees, obtaining
{{ 4, l}, {s, 2) , {6, 3} }, in two steps. Use TableForm to display the results.
4. \VhileJrul\:[icescmcasilybeaddedllsingPlus,matrixmultiplicationismore
complicated. The Dot fi.mction, written as a single period, can be used.
lo[lJ:~ ({l, 2), {3, 4}}.{x, y}
Oulfl]= {x+2y, 3x+4y}
Perform matrix muitiplicatioll Oil {(l, 2), {3,4}} and {x,y} without using Dot.
(This call b", done in two or three steps.)
5. FactorInteger [n] returns a nested list of prime factors and their exponents for the
numher n.
InI2J;= J;'aotorInteger[3628800]
OuI[2J= {{2,8}.
{3,4}. {S,2]. [1,1}}
Use Apply to reconstruct the number from this nested list.
6. Repeat the above exercise but instead use Inner to construct the original numb ern
from the factorization given by FactorInteger [n].
7. Using Inner, write a function div [vus,vars] that computes the divergence ofm
n-dirnensionalvectorBc1dvecs= (el, el, ... , e"jdependentuponnvariahles
van = {Vl, VI, ... , v"}. The diveJ:genceis given by the smn of the pairwise partial
derivatives.
eel eel oe"
--+--+ ... +-OVI OVI OV"
1. Determine the locations after each ~tep of a ten-step one-dimensional random walk.
(Recall that you have already generated the Sl-ep directions in Exercise 3 at the end of
Section 3.2.)
2. Create a list of the step locations of a ten-step random walk on a square lattice.
3. Using Fold, create a function fac [n] that takes in an integer n as argument and
returns the factorial ofn; thatis,1I(n-I)(n-2)· .. 3·2-1.
1. One of the games in the lilinois St3te Lottery is based on choosing n numbers, each
between 0 and 9, with duplicates allowed; in practice, a selection is made from
conwiners of numbered ping pong balls. We c:m model tlIis g:Jme using a simple
user-defined function, wlIich we will alll pick (after the officiallouery mlIIlesofPick
3 and Pick 4).
In[I].= pick[n_l :=Table[RandOJl\[Integer, {a, 9}], {u}]
1n[2}:. pick[4]
OuJ{2}= {O,9,O,4}
This program can be generalized to perform random sampling with nplotemfflt on any
Jist. Write a function chooseWithReplacement [lil", nl, where Iiris tlle list, 11 is the
number of elements being chosen and the following is a typical result.
In{3j:= chooseWithRBplacOOTIlBnt[{a, b, c, d, e, f, g, h}, 3]
Oul]3}= {h, b,
fJ
2. vVrite your own user-defined functions using the ToCharacterCode and From-_
CharacterCode functions to perform the same operations as Stringlnsert and
StringDrop.
3. Cre3te a function distance [II, b] th3tfinds the distance between two points a 3nd bin
the plane.
4. Write a user-defined function interleave2 that interleaves the elements of two lists
of unequal length. (you have already seen how to interleave lists of equal length
using Partition earlier in this section.) Your fllnctiou shollld taketh elists
{1, 2, 3} md {a,b,c,d} as inputs and return {1,a,2,b, 3, c,d}.
5. Write a nested function call that creates a deck of cards and performs a
perfect shuffle on it.
6. Write nested function calls using tile ToCharacterCode and FromCharacter, Code
functions to perform thesamc operations as the bailt-in StringJoin and
StringReversefunctions.
1. Write a compound function definition for the location of steps taken in an n-step
TIlndom walk 011 a square lattice. Hint: Use the definition for the step increments of the
walk as an auxiliary function.
2. The Perfect8earch function defined in Section 1.1 is impractical for checking large
nunlbers because it has to check all numbers from 1 through n. If you already know the
perfect numbers below 500, say, it is inefficient to check all numbers from 1 to 1,000 if
you are only looking for perfect numbers in the range 500 to 1,000. Modify
searchPerfect so that it accepts m-o numbers as input and computes all perfectllumbers
between the inputs. For example, Perfect8earch [a, bl will produce a list of all perfect
numbers in the range from 4 to b.
]. Overload the Perfect8earch function to compute a113-perftct numbers. A 3-perfect
number is such that the sum of its divisors equals three times the number. For example,
120 is 3-perfect since it is equal to three times the sum of its divisors.
In{l):~ App1y[Plus, Divisors [120] ]
OUt[I]_ 360
Find the only other 3-perfect nunlber under 1,000.
You can overload PerfectSearch a~ defined in Exercise 2 above by defining a
three-argum~ntver~ion PerfectSearch [a,b, 3].
4. Overload Perfect8earch to find the three 4-perfectnumber~ less than 2,200,000.
5. Redefine PerfectSearch so that it accepts as input a number k, and two numbers 11 and b,
and computes all k-perfect numbers in the range from a to h. For example, Perfect
Search [1, 30,2] woulrl compute all2-perfectnunlbers in the range from 1 to 30 and,
hence, would output (6, 2 B}.
6. Ifo-(n) is defined to be the sum of the divisors ofn, thenniscalledsuperperji:r:t if a-(a-(n))
== 2 n. Write a fimction 8uperPerfect8earch [a, b] that finds all &uperperfect numbers in
the mge from" to b.
7. Often in processing files you will be presented with expressions that need to be
converted into a format that can be more easily manipulated inside Mathemlltica. For
example, a file may comain dates in the form 20030515 to represemMay 15, 2003.
Mathemlltica represents its dates as a list {yem-, month. day, hour, minutes, seconds}. Write
a functioll convertToDate [n] to convert a number consisting of eight digits such as
20030515 into a list of the form {2003,5,15}.
1. Write a function to sum the squares of the elements ofa numeric list.
2. Write a function to sum the digits of any integer. You will need the IntegerDigo its
function (use ?IntegerDigits, or lookup IntegerDigits in the Help Browser to fino (Jilt
about this function).
3. Using the definition of the distance function from Exercise 3 of Section 4.4, write a new
function diameter [pIS] that, given a set of points in the plane, finds the maximum
distance between all pairs of points. Try to incorporate the distance function into
diameter without naming it explicitly; that is, use it as a pure function. Consider using
Distribute to get the setofal! pairs of points.
1n[IJ:= pts" {Pl' p" PJ}I
In{21-~ DiBtribute[{pts, ptB}, List]
OUlI2J= {{Pl' pd, [Pl' po}, {Pl, p,}, {P2' Pl),
{p" p,), {Po, p,}, {p" p,}, {PJ' l',}. {p" PJ}}
4. Take the removeRand function defined in Section 4.4 and rewrite it as a pure
function.
In[Jj'" removeRand [lie ] ,,,
llelete[lis, Random[Integer, {I, Langth[liBl}]]
5. Convert the deal function developed earlier into (Jne that uses pure functions. Use the
p1.1te function version of the removeRand function from the previous exercise in your
new deal funetion definition.
6. Create a function RepUni t [n] that generates integers of length n consisting
entirely of Is. For example RepUnit [7] should produce 1111111.
7. Create a function choosewi thoutReplacement [fir, u] that is a generalization_ of the deal
function in that it will work with (,my list.
8. Write a pure nmction that moves a random walker from one location on a square
lattice to one of the four adjoining locations with equal probability. For example,
starting at {O,OJ,thefunctionshould return either {O,l), [0, -I), {I,O} or {-I, o}
with equal likelihood. Now, use this pure function withNestList to generate the list
of step locations for an n-step random walk starting at {o, o}.
9. Create a function Wo:r.dsStartingWith [lis, char] that outputs all those words in lis that
begin with the character cbar. As a sample list, you Cln use the dictionary.dat file that
comes with Mathematica.
Here is a platform-independent path to the dictionary file.
1n[4J:~ wordfile"
ToFileName[ {$InstallationDirectory, "Documentation",
"English", "Demos", "DataFiles'}, ITdictionary.dat"]
Oul[41~ C, \Program Files\Wolfram Research\M"thematica\5.1 \
Documentation\English\Demos\DataFiles\dictionary.dat
This reads in the file using ReadList, specifying the type of data we are reading in
asaWo:r.d.
1n[5J;~ words ~ R •• ad.List[wordfi1e, Word] I
10. Modify Exercise 9 above so that WordsStartingWith accepts a string of arbitrary lcngth
as its second argument.
11, A naive approach to polynomial arithmetic would require three additions and six
multiplies to carry out the arithmetic in the expression ax' + bx' +cx+ d. Using
Horner's method for fast polynomial multiplication, this expression Cln be represented
as d + x(c + x(b + /Ix)), where there are now half as many multiplies. In general, the
number of multiplies for an n-degree polynomial is given by:
InI5J:~ sinomialln+ 1, 2]
,
-n
(l+n)
,
Tbis, of coune, grows quadratically with n, whereas Horner's method grows linearly.
Create a function Horner [fir, vm-] that implements Horner's method for polynomial
multiplication. Here is some sample input and the corresponding output that your
function should generate.
1n[1J.'= a:orner[{a, b, c, d},
Ouli7J~ d+x (c +x (b+ax))
In[8J:= Expand[%]
OU/18F d+cx+bx'+ax'
x]
1_ Write a function to compute the Hanuning distance of two binary lists (assumed to be
of equal length), using Select and an appropriate predicate function.
2. All of the implementations of Hamming distance discussed so fur are a bit slow for
large datasets. You can get a significant speedup in running times by using functions
that are optimized for working with numbers (a topic we discuss in detail in Chapter S).
Write an implementation of Hamming distance using the Total function and then
compare running times with the other versions discussed in this chapter.
3. One of the best ways to learn how to write programs is to practice reading code. We list
below a number of one-liner function definitions along with a very brief explanation of
what these user-defined functions do and a typical input and output. Deconstruct these
progrmns to see what they do and then reconstruct them as compound functions without
any pure functions.
a. Determine the frequencies with which distinct elements appear in a list.
In[1j:= frequencies
In[2):~
[lis_] ,_ Map [ ({II, Countllis, II]}) &, union[lis] I
frequencies[{a, a, b, b, b, a, c, ell
Oul[21=
{{a, 3}, lb, 3J, ie>, 2}}
b. Divide up a list into parts each of whose lengths are given by the second
argument.
In[3]:= splitl[lisc,
parts_] ,~
(rnnerITake[lis, {Ill, 112)] &, Drop[#l, _1] +1,
Rest[lIll, List] &) [FoldLiat[Plus, 0, parts]]
In[41:~ splitl[Range[lOI, {2, 5, 0, 3}]
OUt[41= {{1,2}, {3,4,5,6,7}. (},{B,9.10))
This is the same as the previous program, done in a different way.
In[5j:_ eplit2[lie_,
parte_J :_
Map [(Take!lis, II .• {l, O}l)li,
Partition [FoldList !Plus, 0, parts], 2, 11]
c. Another game in the Illinois State LottelY is based on choosing" numhers, each
between 0 and s with no duplicates allowed. Write a user-defined function called
lotto (after the offidallottelY names of Little Lotto and Big Lotto) to perform
sllmplillglvirholit 1'eplacement' on an arbitral)' list. (Note: The difference between this
function and the function chooseWithoutReplacement is that the order ofselcction is
needed here.)
In[6J;_ lottol[lie_, n_] := (Flatten[
Rest[MapThread[Complement, {Rotat!!Right[II], #), 1]]] !OJ
[ N!!stLiet{D!!I!!t!![#, Random[Integer, {I, Length[#]}]] SO,
lis, n])
In[7):~
lottol[Range[lO], S]
Out[7J_ {lO,3,2,7,6]
This is the same as the previous program, done in a different way.
lo{8j_
lotto2[lh ,n_1 ,_Take[TranBpoee[Sort[
Transpoee[ {Table[Random[], {Length[lie]}], lis}] I] U2], n]
As the split and lotto programs illustrate, user-defined functions can bewritren in
several ways. The choice as to which version of a program to use has to be based on
efficien~y. A prognnn whose development time was shorter and which rWlS faster is
betw' than a program which took more time to develop and which runs more slawl}'.
Although concise lVIntbematica programs tend to run fasteot, when execution speed is a
primary concern (when dealing with very large lists) it is a good idea to take variOllS
programming approaches and perform Timing tests to determine the fastesrprogram.
4. Use the Timing function to determine when (in terms of the relative sizes of the list and
the number of elements being chosen) it is preferable to use the differentversions of the
lotto function.
5. Rewrite the pocket Change function in two different ways - one, using Dot, and the
other using rnner.
6_ Make change with quarters, dimes, nickels, and pennies using the fewest coins.
In[9j.'= makeChangel119]
0lJIf-J1= (4,1,1,4)
7. Write a one-liner to create a list of the step locations of a two-dimensional random walk
that is not restricted to a lattice. Hint: Each step length must he the same, so the sum of
the squares of the x-- andy-components of each step should be equal to 1.
8. Write a one-liner version of convertToDate as described in Exercise 7 from
Section 4.5. Consider the built-in function FromDigits.
1. Compute the square roots of 50 and 60 simultaneously, that is, with a single Do loop.
2. Compare the use of a Do loop with using the function Nest (se~ Section 4.3). In
particular, compute the square root of 50 using Nest.
3. Do is closely related to Table, the main difference being that Do does not reLUrn any
value, whereas Table does. Use Table instead of Do in your ~<.>lution to Exercise 1.
"What do you get?
4, Compute Fibonacci numbers iteratively. You will nt'ed to have two variables, say this
and,prev, giving the two most rt'cent Fibonacci numbers, so thatatter the ith iteration,
this and prev have the values Pi and Pi_I, respectively.
5, One additional improvement can be made to the findRoot p~ogTIlm developed in this
section. Notice that the derivative of the function fun is computed each time through the
loop. This is quite inefficient. Rewrite findRoot so that the derivative is computed only
once and that result is used in the body of the loop.
6. Another termination criterion for root-finding is to stop when I .. "; -.1'HII <~; that is,
when two successive estimates are very close. The idea is that if we are not getting
much improvement, we must bc very near the root. The difficulty in progrnmming this
is that we need to remember thc two most recent estimates computed. (It is similar to
computing Fibonacci numbers iteratively, as in Exercise 4.) Progrnm findRoot this way.
7. The built-in FindRoot function is set up so that you can monitor intermediate
computations using the option EvaluationMoni tor.
In{I}:_ xintermed = {}I
FindRoot[x' -50, [x, 50},
EvaluationMonito,,"" AppsndTo[xintermed, xl];
1n{3}:~
xintermed
Ou113J~ {50., 25.5, 13. 730~, 8.68597, 7.22119,
7.07263, 7.07107, ~ .07l07}
ModifY each of the versions of findRoot presented in the text that use a Do or
While loop to produce a fist of all the estimates computed.
f[x],=r-50:
findRootList[f, 50, 0.001]
(50,25.5,13.7304,8.68597,7.22119,7.07263,7.07107,7.07107)
8. To guard against starting 'with a poor choicc of initial value, modify findRootList to take,
as an argument, a fir! of initial values, and simultaneously compute approximations
foreacb until one converges; then return thatonc.
loUI};=
rotateRowsByS[mat_,
s_lwhich
/;[{rotateRight
Length[mat]
~:Langth[S]
,: list}&,
n.
Create
the
function[mat_l
reverse
reverses
in11-1]
the
vec. in
I"UO};~
rotateRows
,,,[we],
Map
[[II]],
h.
c.
Create
Create
aa procedural
function
rotateRight
implementation
[vec,n],
of
where
rotateRows,
vecthe
is[mat
aelements
which
vector
could
and
n is
beadefined
Map [ (rotateRight[mat[IIl],
&), Range[l, Length[mat]]]
RangeS[IIl]]
[1, Lengthlmat]]]
this
functional
(positive orway:
negative) integet.
That
is,
itrotatestheithrowofmatAbvtheamollllrS
[[i]].
Tllatis, it rotates the ith row of mat i -1 places to
the right.
e.
Create
a
function
compress
[lisA,
!isB]
,whereli5A
lisBarc
lists of in
equal
d. Create a procedural function rotateRowsByS, whichand
could
be defined
thislength,
and
!isB contains only Boolean values (False and True), selects out of lisA those
ftlllctionalway:
elements corresponding to TrUE! in lisB. For example, the result of compress r{ a,
b, c, d, e}, (True, True, False, False, True}] should be {a,b, e}. To Imow what size
list to create, you will first need to count thc occurrencesofTrueinli5B.
9. The bisection method is quite useful for finding roots of functions. If a continuous
functionf(x) is such thatf(n) < 0 andf(h) > for tworcal numbers a and b, then, as a
consequence of the Intermediate Value Theorem of calculus, a root off must occur
between a and b. Iff is now evaluated at the Iuidpoint ofa and b, and if
II. Create
a procedural
definition
foroccur
each between
of the following
firstthen
by creating
f(a+b)j2
< 0, then the
root must
(11+ b)j2functions,
and hj lfnot,
it occursa new
InI51:~
list
andMatrixl'orm[matlj
in +theb) elements.
For
eachcan
function,
create
a definition
using atoDo
between
afilling
and (n/2. This bisection
bc repeated
until
a root i,~ found
anyloop
InI9}:~
transposeStruc[mat11
II Mat"ixFonn
In{4j:= transpose[mat_l ,=
OuI[6j1IMalrixFDrm~
10. specified
Using
a While
loop,Table.
write aFor
function
gcdthe
[m,following
n] that computes
greatest
com
and
another
using
example,
functionthe
first
creates
anmon
array of
tolerance.
OulJ9}1(MalnxFo"""
Module [ {matA ~ Tahle[Table[O, {n = Length[matl} l,
divisor
of
m and
n.{a,b,E}]
The
Euclidean
algorithm
for-withinE,
computing
thethe
gcd
of
two numbers
mthe
In[7J:~
MatrixForrn[transpnse[matl]]
the
same
dimension
as mat,
but,:consisting
afOs.
TIlcn inside
Do
loop
it assigns
Definebisect
[I,{m=Length[mat[l]]}]},
to compute
a root
off,
the
method.
Do[matA[i,
j]=using
=
mat[j
,bisection
in,
{i,
InraJ:~
t"anaposeStruc[mat_l
and
n,
assumed
to
be
positive
integers,
sets
'"
=
n,
and
n
m
mod
11. It iterates this
OuFjllMatrixForm=
element
in
position
i} in
matthe
toa gcd
position
{i,j]
matA,
effectively
You
should
give
it0,two
initial
values
and
bandand
assurne
thatf(a)
-i(b)
0; performing
that is, one a
Module
1,
[at{j,
process
until
11 =m},
which
point
of",
n in
is left
in the
value<ofm.
Note
this
same
be
performed
-with
what
referred
as[1]
anot
srrllCtranspose
operation.
Finally,
it{n
returns
since
Do
loop
itself to
do~s
return
{matA
{j,l,n}1;
= Table[O,
~ Length[matl
l,the
{m
= is
Length[mat[
l l}
l}, a
off(a)
andf(b)
iscomputation
positi"",
andcould
the
other
ismatA,
negative.
matA]
[matA
[ [i,{d,
jll e,
: matt
[j, k,
i]]I}}
, ii,Im}, {j, nl]
tured
iteration
Table.
InI51:~
matI
~ {{a,
b, o},
f}, {h,
value.
],k, ,using
o"Table
°
: :: :];]
: :]
[:
, , ,
1. Write the function signum [xl which, when applied to an integer x, returns -I, 0, or 1,
according as x is less than, equal to, or greater than, O. Write it in three ways: using
three ,-,lauses, using a single clause with If, and using a single clause with Which.
2. Extend signum from Exercise 1 to apply to both integers andreals; again, write it in
three ways (though you may use more than three clauses for the multiclause version).
3. Writc applyChar in multiclause fanu, using paltern matehing,on the first element
ofirsargument.
4. Use If in conjunction with Map or Fold to define the following functions:
a. In a list of numbers, double all the positive n1ll11bers, but leave the negative
numbers alone.
b. remove3Repetitions is like removeRepetitions except that ir only alters three or more
consecutive occurrences, changing them to two occurrences; if there are only two
occurrences to begin with, they are left alone. For example, remove3Repetitions
[{ O,1,l,2,2,2,l}] will rerum {O, 1, 1, 2,2, 1}.
c. Add the elements of a list in consecutive order, but never let the SUlll go below O.
In[1j.= positiveSum[{5,
3, -13, 7, -3, 2)]
OUf[lp 6
Since the -13 caused the sum to go below 0, it was instead put back to 0 and the
summation continued from there.
5. UsingNestWhileList, write a function CollatzSequence [n] thatproducc5 the Collatt
sequence fOf any positive integer n. The Collatz sequence is generated as follows:
starting with a number n, ifit is even, then output
if" is odd, then output 3" + 1.
Iterate this process while>! I.
*
T;
1. Using an If fimction, write a funCtiOll gcd [m, n] that implements the Euclidean
algorithm (see Exercise 10 of Section 5.2) for Ending the greatest common divisor of m
and n.
2. Use piecewise to define the pointLoc function given in this section.
3. Extend pointLoc to three dimensions, following this rule: fox-point (x,y, z;), if
z;" 0, then give the same classification as (x,y), with the exception that z;erois treated as
a positive number (so the onlyclassificatiollS Me 1, 2, 3, and 4); ifz < 0, add 4 to the
classification of (x,y) (with the same exception). For example, (1, 0, 1) is in octant 1, and
(0, -3, -3) isin octant 8.pointLoc should work for points in two or three dimensions.
1. Find as many patterns as possible that mat<:h the expressionxA3 + y z.
2. Find as many pattern match~ as possible for the following expression.
{5, erina, {}, "give me a break"}
3. Using both forms (predicate and condition), write down five conditionnl pattern$
that match the expression {4,{a,b},"9"}.
4. In Exercise 10 of Section 5.2, we developed a procedural implement:a.tion of the
E.uclidean algorithm for finding the greatest common divisor of two number$. The
function given in the soJution$ does no argument checking and hence can give
erroneous output for arguments that are not integer$. Rewrite the gcd function given
there so that it uses pattern matching to check that each of it, two arguments are
integers.
5. The function FindSubsequence defined in this section suffers from the limit1tion that
the arguments lis and subseqmllSt both be lists of numbers. \Vrire another definition of
Find Subsequence that rakes inregers as its two argumentS. So for example, the
following should work:
In[rJ:~
pi ~ FromPigits[ RealDigits[N[Pi, 10'] - 3) [[1)));
In{2J:= FindSubseguence[pi,
1415]
OuJ!2j= {{l},{6955},{29136},{45234}. {'79687j. {858BOj,{8B009}}
6. Write a function Co11at~ that takes an mtegerl1 as an argument and returns 312+ 1 ifn
is an odd inregerand returns f ifn is even. Your function Collat~ should attach a
predicate to its argument to check whedler it is even or odd.
7. Write the Collat~ function from the above exercise, but this time attach a condition
instead of a predicate. In ~ddition, YOllr condition should ~Iso check that the argument
to Collat~ is positive.
8. Use alternatives to write a function abs [x] that, whenever x is an integer or a rational,
returns x if x :2: 0, and -x if x < o. \Vheneverx is complex, abs [x] should return ..j re(x)l
+ im(x)'.
9. CreateafunctionswapTwa[lis List) dlatreturnsliswithitsfirsttwoeJements interchanged;
for example, swapTwo [{a, b, c, d, e}) is {b, a, c, d, e). If lis has fewer than two
elementS, swapTwo just returns it. Write swapTwQ using three clauses: one for the
empty list, one for one-element lists, and one for all other list.s. Then \>Tite it using
two clauses: one for lists of length ~ero or one ~nd another for aH longer lists.
10. Convert this definition to one that has no conditional parts (! ;), but instead uses
pattern matching in the argument list:
f[x_, y_l ,=x_Y/; IntegerQ[x]
f[x ,y_l .x[l] + y I: Head[x] ~"List
&&
IntegerQ[First[x) ]
&&y ~~
1
11. Write a version of the HammingDistance function (described in Section 4.7) that uses
Cases instead of Select.
1. Using Trace on maxima and maximaR, explain why the fllIlctional version is much
faster than the pattern matching version of the maxima function.
2. The following compound expression l"etums a value of 14.
z=ll,
In[lj:=
a=9,
OUr[31
~
..
,
..
/.
H
Describe the evaluation sequence that was followed. Use the Trace function to
chel:kyouranswer.
3. Use the Hold function in the compound expression in the previous cxercise to
obtain a value of 12.
,
4. The function definitionf [x_Plus] := Apply['times,x] works as follmvs:
In[4J:= Clear[f,
a, b, c:]
1n[5J:~ f [x_Plus]
,= Apply[Timea, x)
1n[BJ:~ f[a + b + c:]
011/[61= abc
Therewriteruleg[x]:= X I.Plus[z
]-+Times[z] does not work. Use
Trace to see why and rilell modify this rule so that it performs the same operation as the
funcnon f above.
5. Create a l"ewrite rule that uses a repeated replacement to "UlUlest" the nested lists
within a list.
In[7J:= unNeet[{{a, a, a}, {a}. {{b, b, b}. {b, b}}, {a, a}}]
0"1[7]= {{a,
a, a], {a], {b, b, b], {b, b}, {a, a}}
6. Define a function m;ing pattern matdung and repeated replacement to sum the
e1ementsofalist.
7. Using the built-in function ReplaceList, write a function cartesianProduct that takes
two lists as input and returns the Cartesian product of these lists.
In[8J:= "arte1lianProdu"t[{X" x., x o}, {y" y,}]
Our[8]= {{Xl, Yl}, {Xl. y,}, {x., Yl}, {X" y,], {X], Yl}, {X], Yo}}
8. The function CellularAutomaton [nde. init, t] creates a list of rile evolution of a cellular
automaton. For example, this geueI:ltes five iterations of the cellular automaton rule
number 30 starting with the initial condition of a single 1 surrowlded by Os.
In[9]:=
CellularAutomaton[30, {ill, O}, 5]
oul[ej=
{{O, 0, 0, 0, 0,
}O, 0, 0,
'0,
"
0, 0, 0, 0, O}, 10, 0, 0, 0,
0, 0,
0, 0,
0, 0, 0,
'.o. "
" "
"
0,
"
o}.
'0. 0,
,. " "
0, 0, 0,
o}.
0,
o}
q
.
0.
" " '. '. " "
o}. I'.
'.
'. " " " '. " "
0,
0,
Write a function CAGraphics {lis] that takes as argument, a list generated by
Cellular-Automaton and produces a Graphics object that can then be displayed directly
with Show. Your function should use RasterArray and also aset of rules to transform
each 0 and 1 into different color directives such as Hue [ .2] .
In[l0J:= ca30
~ CellularAutomaton[30, {{1}, O}, 500] I
InI11]:= Show[CAGraphic1l[ca30]]
0uI{11l=
_Graphics_
j
1. Modify the Caesar cipher so that it encodes by shifting five places to the right.
2, Modify the alphabet permutation cipher so that instead of being based on single letters, it
is instead based on adjacent pairs of letters. '\Vhereas the sing Ie letter cipher will have
26! '" 40329146112660563558400000Cpermutations, the adjacent pairs cipher will have
262! permutations - a very large number.
InfIJ:~ ]I"[26'!]
Ou/flr- l.883707684133BIOxlO""
K.
J.
3. You can quickly create a graphics function to plot binary data (Os and Is) using
Raster. For example;
InfzJ;= data ~ Table[RandOlll[Integer], {5}, {5}]
0"1[2]= {{l,l,O,O,l},{l,O,l,l,O},
(O,l,l,l,l),{O,l,O,l,l).{O,l,l,l,O))
In[31'~ Show[Graphice [Ra.ster[Rever~e[data]
Automatic]]
OUI[3)=
•
J, AspectRa.tio ...•
••
Graphics-
lEyou wanted to color the squares with color directives such as RGBColor or Hue or
GrayLevel, then you need to use RasterArray iMtead. Create a function matrixPlot
[mat,rules] that takes a matrix milt as its £irst argument and a list of rules as the second
argument. The list of rules should specifywhatcolordi rective each of the values in milt
should be mapped to. Finally, compare your function with ArrayPlot (new in Version
5.1).
1n{4J:= Arra.yPlotldata, ColorRules ...• {O ...• Black, 1 ...• White}];
•
•
6. Create a function ratatePlot [gr, S] that takes a plotgr and rotates it about the origin by an
angle
fl.a For
example,
to rotate
a plot
function,
first
create
plot:Then gr
7.
function
rotatePlot3D
1>,ofthcsine
e,!/I]
that
will
rotate
areverse
Graphics3D
5.
Plot
the
function
sin(xy)
withxandy
taking
on2Jr]
values
from
0 to the
31[/2.
4. Create
Plot the
fimction
sin{x)
over
the[gr,
interval
[-2Jr,
and
then
the x- object
and use a
-~ ofPlot
1n{5J:_the
plotl
[Sin
[x] ,rp,
{x,
0,
2 r/J
If}];
about
origin
by
dle
angles
and
inshifting
the x,y,the
andgraphic
7,; directions,
transformation
I"lIle
topoint
perform
a6,shear
by
in therespectively.
x-direction by a
J'-coordinates
each
by means
of
a transformation
rule.
Then
of1[radians.
factor
In[6J."=perform
rotatePlot[plotl,
of four.
_0.', the rotation",];
Before doing the exercises in this chapter, you may want to take a look at Appendix B,
which discusses some cornmon programming errors, and how to debug nx:ursive
functions.
1. For eachofdle following sequences of numbers, see if you can deduce dle pauern and
write a Marhemmim function to compute the ith V:llue.
2,
6,
18, 108,
1944, 209952,
"
A,
A,
1,
-1, 2, -3,
5, -8,
13, -21,
B, E, E, B, B,
B, E,
E, E,
, A,
b
0,
.
A,
A,
A,
A,
•
0, 1, 2, 3, 6,
11, 20, 37, 68,
2. The numbers FA" represent the number of additions that are done in the course of
•• C, C, C, C, C, C, C, C, C,
evaluatingF[,']'
2 4 FA4 7
FAs
FA6
WritE a function FA such that FA[n] = FA".
12 20 33 FA7
FAs FA9
1. Write a recursive function sumOddElements [/is] that adds up oulythe elements of the
jist lis that are odd integers. lis may contain even integers and nonintegers. (Use
IntegerQ to determine if a given element is In integer.)
2. Write a recursive function sumEveryOtherElement [lis] that adds up
lis [[1]], lis 1 [3} 1, lis [[5]], etc. Each of these elements is a nurnber. lis may hJve any
number of elements.
3. "Vrite a function addTriples [lis" Iis2, lis,] that is like addpairs in that it adds up the
corresponding elements of the three equal-length lists of numbers.
4. Write J fun~1:ion mu1 tA11Pairs [bs] that multiplies evety consecutive pair of
integers in the numerical li&'tlfs.
In{lJ''~ m.u1tAllPairs[ {3, 9, 17, 2, 6, 60}]
0111[1J_ {27,lS3,34,12,360}
). Write the function maxpairs [lis " lis2] which, for numerical lists of eqnallength, returns
a list of the greater value in each corresponding pair.
6. The function interleave [lir,,!i;-2], which merges lWO lists of equal lcngdl,can be
defined as follows:
Ini2J:~ :l.nter1eave[lisl , 1:1.s2 ] ,~Flatten[Transpose[ {lisl, lis2}]]
In[3J:~ inte:deave[ {a, b,
oJ, {x, y, 2J]
Ou1{3J= la, x, b, y, c, z}
Rewrite interleave usiugrecursion.
1. Write the function prefixMatch [lir1 ,iis2] that finds the starting segments oflh, andlis2
that match.
Inll):: prBEixMatch[{l, 2, 3, 4}, {l, 2, 5}] Oul[1]=
{l,2}
2. Modiry- nmEncode so that it leaves single elements as dley are.
InI2):~ runEncode2[{9, 9, 9, 4, 3, 3, 5}]
OuI[2]" ({9, 3), 4, {3, 2}, 5}
For this version, you need to assume that dle argument is a list of atoms, otherwise the
output would be ambiguous.
3, Modiry- one of the TunEncode functions so that it produces output in the same fonn
a~ the built-in Split function.
1n[3):~ Splitt {9, 9, 9, 9, 9, 4, 3, 3, 3, 3, 5, 5, 5, 5, 5, 51]
Oul[3F ({S, S, 9, S, 9), (4), {3, 3, 3, 3}. {5, 5, 5, 5, 5, 5j}
4, A slightly more efficient version of runEncode uses a three-argurnent auxiliary
function.
runEnc:ode[{}l,"{}
runEncode[{x_, r __ }l ,. runEncode[x, 1, {r}]
runEncode [x,k, {r}] computes the compressed version of {x, x, x, ... , x, '-), where the xs
are given k times. Define this three-argument function. (Note dlat it is legal to have a
function be defined for different numbers of arguments; nlles in which runEncode
appears on dle left-hand side "With two arguments will only be applied when runEncode
is called with two arguments, and likewise for the three-argument version.) Using the
Timing function, compare the efficiency of this version "With our earlier version; be sure
to try a VlIriety of examples, including lists that have many short runs and ones that have
fewer, hnt longer runs. You will need to use Table to generate lists long enough to see
any difference in speed.
5. maxima can also be computed more efficiently with an auxiliary function.
maxima[{}] ,: {}
maxima[{x_, r __ }] ,:maxima[x, {r}]
The two-argument version has this meaning: maxima [x, lis] gives the maxima of the
list Join [{xl ,lis]. Define it. (Hint. the key point about this is that
maxima [x,lir] is equal to maxima [x, Rest [lis]] if x '" First [lis].) Compare its efficiency
"With the version in the text.
6. Write the function runDecode, which takes an encoded list produced by runEn·, code
and retuTn~ its unenl.-"Oded foon.
Inr41"~ runDecode[{[9, 5}, {4, l}, (3, 4), {5, 6}}]
Ou1141~ {S, 9, 9, 9, 9, 4, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5}
7. The code we developed to compute the k-e1ement subsets of any given list differs
from the built-in Subsets function in that the]atter has a mechanism for generatingaU
subsets of length less than or equal tok.
In{51:~ A" (a, b, C, d);
Subs •• ts[A,2]
oul16p {{}, {a). {b}. {e}, {d], {a, bL
{a,c},{a,d},{b,c},{b,d},{e,d}]
Uyou want to get rmly two-element subsets you use a slightly different form.
1n[7]:~ Subs •• ts[A, {2}]
Oul{7p {{a, b), {a, e], {a, d}, {b, e}, {b, d}, {e, d]]
Modiry- the function subsets developed in this section to take either form,
subsets [lir, k] or subsets [Iir, {k}] so that it mimks the behavior of the built-in
Subsets.
I. Add rules to ddx for the trigonometric functions sine, cosine, and tangent.
2. VVhen variables other than x are present in an expression, the rules for differentiation
with respect to x actually do not change. That is, elCpressiollS that have no occurrences
of x are treated like co.ostant~. So there should be a rule that says ddx [u] _0, if x does
not occur anywhere in il. Define the function nox [el to return True if x does notoccnr
within e, then add the new rule for those expressions. You will need to use the
comparison function ~ l~, called ITnsameQ, which tests whether two symbols are
l.meqnaJ; the usual Unequal comparison (1 _) cannot be used to compare symbols.
3. Define a two-argument version of ddx whose second argument is the variable with
respect to which the derivative of the expression is to be computed. Thus, ddx [u, xl will
be the same as our cnrrent ddx [ul. You will need to determine when an expression ha~
no occurrences of a variable; YOIl can Ilse the built-in function FreeQ.
In{3J:~
In{4}:=
catNodes[fruittree]
h:uittree =
OUJ!Bl=
(7,91
11,
S.7.
I. The
A,;suroe
The
MergeSort
Gaussian
aof
function
now
that
elimination
function
listLevel
your
tree's
procedure
[tr
,fJ]
labels
inwhich
this
are
can
section
gives
all
fail
strings.
for
abecomes
list
a variety
of
Write
anquite
thelabel~
of
a{Africa}}
function
reasons.
slow for
inofWe
treetr
to
moderately
concatenate
have
at leveln,
already
sized
ItWrite
{WOrld,
can
be
{Asia},
repre~ented
{Europe},
as
a,=list,
(America,
{North},
{South}},
InI5J:~
ba1anced[{
}]defined
True
trees
arbitrary
degree,
one
node
have
any
(finite)
munber
children.
6.8, In
9.
A
Program
tree
is
said
the
function
to be {"date",
baUmud
that constructs
if,{"kumquat'},
for
every
a=
Huffulan
node,
theencoding
heights
of
tree,
its as
children
shown
differ
in tilefrom
last part
{"fig",
{"papaya"}),
{"mango")}/
ou1j41~ £;'gdatekumqu<>tp<>p<>y<>mango
ba1anced[L,
1c_,
rc_l]
._
the
lise,.
mentioned
where
~trings
Perform
the
root
in
that
some
depth-fim
is
atlcvel
will
experiments
not
order.
its
childrenareatleve1],
good
This
to determine
results
is the
for
if the
theyou
itsgrandc
Hilbert
bottleneck
getroot
by
matrix,
following
is caused
butchildren.
themostly
the
reason
2,andsoon.
lefunost
byfor
thethis
Write
functions
height,
and
printorder
Tree
for
trees
ofhildrenatlevel
any
degree.
Represent
such
aitminInTree,
tree
by
a0,give
list
label
of
the
its
For
one
of
this
another
section.
by no
more
than
I;containing
that is, thethe
difference
in
heightalld
between
the taller
child
ba1anced[lc]
&&balanced[rc]
&&Abs
[height[lc]
height[rc]]
auxiliary
isIn{B}:=
quiteliatLevel[numbertree,
subtle
merge
and
function
we
will
postpone
the
double
our
recursion
explanation
inside
to
MergeSort
Section
8.5.on
itself.
Another
reason
you ~
have
it1
children
of
any node
asfollowing
faroras
possible
before
visiting
their
siblings
the Once
right.
example,
consider
trce:
and
the shorter
is 0the
or 1.
(fruittree2]
is balanced, butnumbertree from Exercise 4 is not.)
10, Write
more
efficient
version
ofcomputing
encodeString
that
creates
of a 11 the
This
isa very
expensive
due
tono
theW~1d
of heights
of subtrees.
For example,
it
identified
can fail
isthe
that
cause
thereofmay
the
be
problem,
unique
try solution
to rewrite
atMergeSort
all; consider,
to afortable
Note that the condition must hold
atoll nodes, not just the root. Here is a funcuon to
encodings
tlle characters
given of
tree,
applies involves
the tablevisiting
to the list
of
first
checksoftheallheight
of the twoina
children
the then
root (which
every
overcomethebottleneckissue~.
example,thefollowingsystem.
test whether a tree is balanced.
characl-ers.
Thisexcept
table can
represented
a listit of
rewrite
rules,on
like"
a"-)
node in the tree
tlle be
root
itself), andastllen
calls
balanced
those
two children,
XI + x;. ",0
{o,
1, l},
which
can then
applied
to the
list of characters
usingReplaceAll
(I.).
which
then
computes
thebe
height
of their
children
/0,- the ,econd
time.
2Xl + 2 x;. ",0
To avoid this extra cost, define a function balancedHeight [t] that returns a list of lWO
Here,
the two
equations
essentially
thethe
same,
so we
not have
enough
information
elements:
lhe first
is the are
height
of t, and
second
is ado
Boolean
value
saying
whether t
to balanced.
determineThen
Xl and
Xl uniquely.
problem
is
you
can defineThis
balanced
by is inherent in this system and cannot be
solved,
no matter how sophisticated an algorithm we devise.
In[7j:~ balanoed[t_] '" balanoedHeight[t] [2]
There is, hmvcver, another kind of problem that we should be able to overcome. It is
illustrated by the following system.
0u1j21~ 52
XI
+xz+XJ = 1
xl+",+2x)=2
Xl
+2X2 +2XJ = 1
Our elimination procedure will produce the smaller system corresponding to the call
solve[{ {O,l,l}, [l,l,O}}].
XJ =
1
x;.+X} =0
L.
This system obviously does have a solution, but solve will fail because, in attempting to
eliminate Xl, itwiIl compute the new coefficient of X) as I which involves a
division by 0.
The solution to this problem is easilyf01.md by observing that in any system of equations,
changing the order of the eqnations does not change the solution. Thus,
theabovesystemiseqmvalentto:
3. Suppose
we could find lowcr triangular and upper triangular matrices, Land U, such
that
A =L
x;.+X3
=0U. Then for any vector B, we could easily compute solve[A,Bl by
computing
[U, solveLower [L, B]]. (Note that\! vector X is a solution to tile
x} = solveUpper
1
original system whenAX = B. But this implies that I, U X = 8, which implies that there
is
a vector
Y such
thatLY
= Band
UX = atY;all.
solveLower [L,8] isY, and solveUpper[U,Y]
solve
has no
difficulty
with
this system
isX.)
Modify solve such that it reorders the rows of its argument to ensure that all is
So,
given
a roery
square
mau'ix
can find
such
athe
decomposition
of be
A,
then
we can
non-D.
row
has 0A,this
asif we
its
first
element,
solved.)
This
It
Can
be(Ifshown
that,
when
comtructiou
works,
assystem
it doescannot
in tllC
same
situations
efficiently
~olveA
X = the
BI, for
B. In fact, finding this so-called LU-dw'jmposition of
process
reordering
is calledpivotillg.
in
whichofsolve
works,
Uequations
'"any
A. given
A
is verytwo
similar
to doing
Gaussian elimination. Specifically, suppose thatA' is the
Program
versions
of LV-decomposition:
2. In
Exercise
I above,
suppose
A is known to be UppfTtrilmg;ular, meaning it has Os
smaller
matrix produced
by two
tile elimination
processas(that
the coefficients
system
a.
LUdecompl
[A]
returnS
I, and
justis,
described.
That
is,in
it the
below the diagonal (formally, aijmatrices
= 0 for all
i > U,
J). Define
solveUpper,
having
the
S'),returns
and suppose
nuther tllatA'
= Ii U', where L' is lower triangular and U' i~ upper
a list containing
these
twothe
matrices.
same
arguments
as solve, but
under
assumption thatA is upper triangular. (Thi~ i.~
triangular (so L' and U' can be computed recursively), Then consider the following two
,.[A]solve,
1 0 than
0returns
much
simpler
since
requires
no elimination.)
Then
define
sol veLower,the
a.
LUdecomp2
oncitmatrix
which
contains bOtil
I, and
U, specifically,
'u
'u
...
matrices
U
and
L.
E!.L
4. Suppose
you
have
a
tree
all
of
whose
labels
are
numbers.
Write
a
nmction
toforget
sumrow.
all
the
I,0same
is (L
L' with
following
theArow
(I, 0,!nother
0, ... ,0)words,
as tile
top
withmatrix
arguments,
but
forchanges,
the
where
is
lowertritmgular
(has
Os
nbrwe
the
-l) the
+ U,
where!
is case
the add
identity
matrix.
the
Lo
Uo
the
labels.
""
diagonal).
 For
U issol
the
U'
veL
left
with
ower
theoffirst
should
rowthe
work
of multipliers
coefficients
byallIs)
manipulatingA
computed
of just
A added
so
in the
as
astlle
to
the
elimination
make
top row,
it upper
and
process;
added
that is,
diagonal
elements
L add
(which
are
and
place
elements
of
LOs
below
L' U'column,
triangular,
In{l}:~
numbertree"{4,
and
then
{5},
sol veUpper.
{6,
{9,above
{lO},
In{2}:~
aumNodes[numbertree]
Uis,
as
course,
the
quotientsa;ljoll'
leftco!umn'
upper
theofthe
diagonal
and calling
tlleu·iangular.
elements
of {7},
U at or
theill}}}},
diagonal in a single matrix.
-if,
""
1. Using dynamic programming is one way to speed up the computation of the
Fibonacci numbers, but another is to use a different algorithm. A much more efficient
algorithm than F can be designed, based on the following identities.
F'R =2F"_lF,,+F;,
F2,,+1 =F~+l +F~,
forn;"l
forn",!
Program F using tbese identities.
2. You can still speed up the code for generating Fibonacci numbers by using dynamic
progranuning. Do so, and construct tables, like those in this section, giving the number
of additions performed for various n by the two programs you have just Wl·itten.
3, Calculation of the Collatz numbers, as described in Exercise 5 from Section 5.3, can be
implemented using recursion and sped up by u~ing dynamic programming. Using
re<:-"ursion and dynamic programming, create the function collatz [n, i], which
computes the ith iterate of the Collat'l sequence starting with integer n. Compare its
speed with that of your original solution.
1. Write rec\lIsive definitions for Fold, FoldList, and NestList.
2. Recall the notion of a random walk on a two-dimensional lattice from Chapter 3.
Use repeat to definc a special kind of random walk, one which continues until it steps
on to a location it had previously visited. That is, define landMineWalk as a function
of no arguments which produces the list of the locations visited in such a random walk,
starting from location (0, Dj.
1.
Define a function complexToPolar that converts complex numbers to their polar
representations. Then, convert the numbers 3 + 3 i and e'ic to polar form.
2.
Using the built-in Fold function, \VJ."ite a function convert [lis, b] that accepts:t list of
digits in any base b (less than 20) and converts ittoabase 10 number. For example,
110b is 13 in base 10, so your function should handle this as follows, Ifl[jj:~
convert[{l, 1, 0, l}, 2]
3.
Write a function sumsOfCubes [n] that takes a positive integer argument n and
computes the S1lJ;IlS of cuhe.~ of the digirs of 'Fl. Tills exercise and the next three
exercises are excerpted from an article in The Mathematira Journal, Sums of cubes of
digits, driven to abstraction (Hayes 1992).
4. UseNestList to iterate tbis process of summing cubes of digits; that is, generate a list
starting with an initial integer, say 4, of the successive S1lJ;IlS of cubes of digits. For
example, starting with 4, the list should look like: {4, 64,280,520,133 , ... }. Note, 64",
4J, 280 '" 6J + 43, etc. Extend the list for at least 15 values and make an observation
about any patterns you notice. Ex:perimentvr.ith other starting values.
5. Prove the following ~tatements'
a.
Un has more than four digits, then sumsOfCubes [n] has fewer digits dIan n.
b. Un has four digits or less, then sumsOfCubes en] has four digits or less.
c. Un has four digits or less, then sumsOfCubes [n]" 4.93.
d. Un isless than 2,916, then sumsOfCubes [Il] is less than 2,916.
6. Write a function sumsOfPowers [n. p] that computes the sums of pth powers of n.
7.
Binary shifts arise in the smdy of computer algoriduns because they often allow you to
~peed up calculations by operating in base 1 or in bases that are powers ofl. Try to
discover what a binary shift does by performing the following shift on 14 (base 10).
First get the integer digits of24in base 1.
1~2t~
IntegerDigita[24, 2]
OUl[2J~ {1, 1, 0, 0, OJ
do a binary
shift, onefrom
place
to the right.
8. Then,
The survivor
[nJ function
Chapter
4 can be progranuned using binary shifts. This
13. Numerous tests are available for determining the effective "randomness" of a sequence.
can beRotateRight[%]
done by rotating the base 1 digits of the numbet n by one unit to the left and
1n[31;~
One of the more fundamental tests is known as the X~ (chi-square) test. It tests to see
then
converting
this
list back to base 10. For example, ifn" 10, the base 1
OUl[JJ~
10, )., 1,
0, rotated
O}
how evenly spread out the numbers appear in the sequence and uses their frequency of
representation is 10102; the binary shift give~ 01012; converting this number back to
occurrence.
If n is thetoupper
bound of a sequence of m positive llumbers, then, in a
Finally,
base 10 convert
gives 5,back
which isbase
the 10.
output to survivor [5J. Program a new survivor function
well-distributed random sequence, we would expect about m /n copies of each number.
AA
using 2athe
binary chiSquare
shift.
1n{41:~
\Vtite
function
OllOO
[lis] that takes a list of numbers and l'ewrns thex~ statistic.
To take into account the acmal frequencyvr.ith which each number OCl."Urs, the Xl test
9. You
Simulate
dIe throvr.ing
two dice
by defining
afor
function
rollEm
when evaluated,
Out[4[=
will12find
built-inofCount
function
helpful
thethat,
frequencie~.
Implement
thethe
linear
method
andthetest
it calculating
with fi
a variety
of
numbers
m andof i
is implemented
by thecongruential
formula below
where
function
is the number
of copie~
displays
two
integers
and
starting
value
isbetween
theseed,
dle6.m/1I1tipliel',
m is the
moduh«. Recall
14. The
Determine
the
X~ xo
~tati,~tic
for1b ais
seqllence
of 1000and
integers
generated
with thethat
linear
you
find that
the
innumber
a loop
try
aiseven
large
value
for
themake
modulus
in If
the
If
thegenerator
Knumbers
statistic
is m,
close
to
n,easily,
then
the
are rongruNJtioi
reasonably
random.
11.
12. b.
A
Write
surprisingly
asequence.
function
simple
quadCong
pseudorandom
[a, b,gets
c,two-dimensional
xo]
that
algorithm
implements
the
ausing
quadratic
linear
wngrumtial
method.
method,
Experimentvr.ith
other
(including
both
oddimages
andnumbers
integers)
and
10.
Experimentwith
creating
random
ListDensity'"
Plot.
381,b",
15,and
a starting
value ofO. in1VInthe'!natim as
7congruentialmethodwitb'J1t'"
mod
5
is
the
temainder
upon
dividing
7
by
5.
This
is
represented
Inisparticular,
we
consider
thehas
sequence
sufficientlyranuomifthestatisticiswithin2.,fii
It
whete
quite
n, Knuth
b,easy
and
to
c will
are
implement
the
been
m isofthe
studied
modulus,
extensivcly.
andgenerating
xo Sequences
is the starting
of random
value. The
m.
(See
1997
for
aparameters,
fulland
treatment
random
number
algorithms.)
some
conjectures.
X",.I "'(a~+bx,,+c)
InI51:~
Mod[7,
5]
ofll.
X"+I"'X1Jb+1
(modm)
numbers
iteration
aregiven
generated
by: modm
by a formula such as the following'
Oul[Sj=
2is
15. John von Neumann, con~idered hy many to be the "father of computer science,"
sugge~ted a random number generator known as the middle-sq1Mn method. Starting
with a ten-digit integer, square the initial integer and then extract its middle ten digirs
to get the next number in the sequence. For example, starting with 1234567890,
squaring it produces 1524157875019052100. The middle digits are 1578750190, so
the sequence starts out 1234567890, 1578750190,4521624250, .... Implement a middle
square random number generator and then test it on a 1,000number sequence using the:!
test. Was the "father of computer science" a good random number generator?
1. Explain why Matbf:matica is unable to produce a number with 100 digits of precision in
the follQwing example.
Inrl].'= N[1.23, 100]
Oul[l~ 1.23
1n{2J:~ Precisionl%]
Oul[2J~ MachinePrecision
2. Determine what level of precision is necessary when computing N [..J2 , pree] 2DO to
produce aCCUl"acy in the output of at least 100 digits.
3. Explain why the following computation produces an unexpected result (that is, why the
value 0.000000000001 is uot remrned).
In{aJ:~ 1.0 - O. 999999999999
OUI[aJ= 9.99978xlO·n
4. How close is the munber e{f6'f to an integer? Use N, but be careful about the
precision of }'Dill computations.
1. Create a function RandomSparseArray [n] that generates an nxn sparse array with
random numbers along the diagonal.
2. Create a function tridiagonalMatrix[n,p,ql thatCreatesannxnmaU"ixwith the integer p on
the diagonal, the integer q on dIe upper and lower subdiagOllals, and Os everywhere
else.
3. Create a vector vec consisting of 100,000 random real numbers between a and 1.
Check that it is indeed a packed array by using Developer - PackedArrayQ. Then replace
one element in vec"With an integer. Check that this new vector is not a packed array.
Finally, perform SDrne rnemDfY and timing tests Dn these two vectors.
1. The newton function developed in this section suffers from several inefficiencies.
One of them is that if the precision goal is no more than machine precision, all
intermediate computations should be done at the more efficient machine precision as
well. Modify newton so that it will operate at machine precision if the precision goal is
at most machine precisioll.
2. In the newton program, we added Set precision [result,precisionGoal] at the vcry end to
return the final result at the precision goal, but we have done no test to insure that the
result meets the required precision. Add a rest to the en dofthe newton [unction so that, if
this condition is not met, an error message i~ generated and the current result is
output.
3. Some functions tend to cause root-finding methods to converge rather slowly. For
example, the function f(x) '" sin(x) - x requires over ten iterations of Newton's method
-..vith an initial guess of Xo = 0.1 to get three-place accuracy. Implement the following
acceleration of Newton's method and determine how many iterations of the function
[(x) = sin(x) - x, starting -..vith XQ = 0.1, are necessary for six-place accuracy.
accelNewton(x) '"
f(r)f'(r)
li'(x)]'-f(x)f"(x)
This accelerated method is particularly useful for functions -..vith multiple roots.
4. Write a functional implementation of the secant method. Your function should accept
as arguments the name of a fi.mction and two initial gues.\es. It should maintain the
precision of the inputs and it should output the root at the precision of the initial guess,
and the number of iterations required to compute the root. Consider using the built-in
functions Fixedpoint orNest.
5. The norm of a matrix gives some measure of the size of that matrix. The norm of a
matrix A is indicated by 11A11. There are numerous matrix norms, but all share certain
properties. FornxJJ matrices A andB:
(i)IIAII;o:O
(ii) IIAII = o if and only if A is the zero
matrix (iii)IIcAII= IclllAllforanyscalarc
(iv) 1111 + Ell'" IIAII + IIBII
(v)IIABIl $ IIAIIIIBII
One particularly useful norm is thc I"" norm, sometimes referred to as the m1lX nO'rIlZ. For
a vector, this is defined as
6. If a matrixA is llonsingular (that is, is invertible), then its condition number c(A) is
defined
as IIAII·IIA-lil. Amatrix
is called
7vell-conditioned
if its condition
number
is
7. This
An
additional
linear
systems
equations
known
scaled
computestechnique
the sum offor
thesolving
absolute
values
of theofelements
in iseach
row,asand
then
closecorresponding
to 1Assuming
(the
number
thea matrix
identity
matrix).
Amatrix
is
ill-condipivoting.
that then
no
column
of
contains
all
(incalled
which
there
The
matrix
norm
isofdefined
Hence,
forOs
a the
matrix
=case
aij,
we
Once
such
a k iscondition
found,
the ith
row
andsimilarly.
themat
row
arc
interchanged.
The
scaling
takes
the
maximum
of
dlese
sums.
That
is,
the
100kth
JUatrix
norm
isis
maxAof
thc
100
would
be
no
unique
solution),
then,
fOJ"
each
row,
a
scale
factor
determined
by
tioned
if
its
condition
number
is
significandy
larger
than
1.
hm
itself
isofonly
for that
comparisou
purposes
so no additional
error
is
norms
the done
rows.
sclecting
element
is the largest
in absolute
value; thatroundoff
is, in row
i ,thesca]e
factor
Write
a
function
conditionNumber
[mat]
thatus~s
the
norm
you
defined
iu
the
previous
is defined
as
=norm
maXl~j~"
I Infinity],
flij I. Nowwhich
a row takes
interchange
is matrix
determined
finding and
the
introduced
bySithe
scaling
factor.
Write
a function
[mat,
a square
as anby
argument
first
integer
k
such
that:
exercise
as
an
auxiliary
fUllction,
and
outputs
the
condition
number
of
mat.
Use
condi
Write
function
solnorm.
veSPPCompare
that implements
scaled-..vith
partialthe
pivoting
thefunction.
above
outputsa its
11·1100
your function
built-inusing
Norm
tionNumber
to
compute
the
condition
number
of
the
first
ten
Hilbert
matrices.
desCl1ption.
1. Create a primitive color wheel by coloring successive sectors of a Disk according to the
Hue directive,
2. Create a graphic that contains one each of a circle, a triangle, and a rectangle. Your
graphic should include an identifYing label for each object.
3. Create a three-dimensiunal graphic containing six Cuboid graphics primitives,
randumly placed in the unit cube.
4. Create a graphic that consists of 500 points placed randomly in the unit square. The
points should be of random radii between .01 and 0.1 units, and colored randomly
accordingtOGHuE!:function.
5. Create a graphic that represents the ~olution to the following algebraic problem that
appeared in Porta, Davis and Uhl, 1994. Find the positive number~" such that the
folIowing system has exactly one solution in.1' and y.
(x_I)2
+0'_1)2
=02
(X+3)2 +(y_4)2 =or2
Once you have found the right number r, then plot the re~ulting circles in true scale on
the same axes, plotting the first circle with solid lines and the two solutions with dashed
lines together in one graphic,
6. Load the package Graphics'polyhedra' and then display each of the solids defined in
the package, including Tstrahedron, Octahedron, Icosahedron, Cuboid, and the
Dodecahedron.
7. Create a graphic of the sin:function over the intetv'.ll (0, 111-) that dispJaysver tical
lines at each pointca1culated by the Plot function to produce its plot.
1.
Create a function ComplexListPlot that plots a list of complex numbers using the
ListPlot function. Setinitia! options 50 that the PlotStyle is n:d, the PointSize is a little
larger than the default, and the horizontal and vertical axes are labeled "Re" and "1m,"
respectively. Setitup so that options to ComplexListPlot are pa.~5ed to ListPlot.
2. Create a function RootPlot that plots the complex solutions to a polynomial in thc plane.
Use your implementation of Complex List Plot that you developed in the
prevlOIlSeXerC15e.
3. Modify the function RootPlot so that you can pass the options from Plot to the
auxiliary function fplot. You will need to use the Utilities 'FilterOp-,. tions' package to
pass these options.
4.
Add some error checking to DataPlot so that a message is returned if the data that are
passed are not a one- or two-dimensional list. Yow- message should be of the following
form,
InflJ:~ DataPlot, ,baddim ~ 'The data used by DataJ?lot must be in
the form of a one_ or two-dimensional list." I
Then modify the Which statement inside DataPlot so that it continues to do the right
thing if the data that are passed are a one- or two-dimensional list, but, if not, the
baddim message above is returned. For example, something like the following
willwotk.
In[2j."= pts : Which[
VectorQ[data], Maplndexed[ {II2 [[111, Ill} &, data],
Dimensionll[data] [[2] J " 2, data,
True, MesIlage[DataPlot, ,baddhnJ I $FailedJ I
5.
Although the program simpleClosedPath works well, there are conditions under which it
will occasionally fail. Experiment by repeatedly computing simpleClosed ' .. Path for a
set of ten points until you see the failure. Determine the conditions that must be imposed
on the selection of the base point fo:r the p:rogram to wo:rk consistently.
6. Modify simpleClosedPath so that the point with thesmaIlestx-cooI"dinate afthe list of
data is chosen as the base point.
7. Modify simpleClosedPath so that the point that has the largesty-coordinate is chosen
as tile base point.
8.
Write a function triangleArea that computes the area of any triangle in the plane given a
list of the three coordinate points that describe that triangle.
9. Write a function pointInPolygonQ that tests whether a given point is inside a
specified polygon. For example, the origin is inside the polygon formed by joining
the four unit vectors:
Figure 9.5: A tricky tree to draw
13. Another
difference between the tree-drnwing code we have shown here and tile code
that was nsed in Chapter 7 is that the algorithm there was able to draw trees with labels
at the nodes. Extend your algorithm from Exercise 13 to add labcls; your trees
shouldh:rvestringsasrheirlabels.Youneedtotakethe-widthofthelabeisinto account when
computing the separation tree (this is a change to placeTree), and make sure the lines do
nor inteI:sect the labels (this is a change to drawSepTree). Unfortunately, there is no
way to compute the exact width of a text string as it will appear in a Mathematica
graphic; just approximate using tile number of characters in the label.
12. 111e tree-drawing code we have presented is not the same code we used in drawing the
10. A
polygon
is caned
convex
a linedrnwn
connecting
any 9.4
twoshow
pointsthe
inside
the polygon
lies(a) is
trees
in Chapter
7. The
twoif trees
in Figurc
difference:
drawing
inside
the polygon.
Most
of is
the
simple
closed
polygons
we computed
11. completely
Another
the
one produced
way
of finding
byplaceTree,
a simple
and
closed
(b)
path
tile
is
one
to produced
start
with
by
anythe
closed
algorithm
path and
usedin
inthis
section
are
Forisa due
given
set
of nintersections
points,
find and
those
pointsand
which
form
Chapter
7. nonconvcx.
Thatmake
algotithm
Reingold
and TilfOJ:d
(1981),
basically
p:rogressive\y
it simpler
bytofinding
changing
tile
path
to awhat
avoidit
Program
this
tree-drnwing
algorithm.
There
is
one
tricky
part
to
it,
which
we
will
convex
polygon
a of
boundary
for
the
entire
point
set.a closed
(The
such
does
just this:
instead
basing
of with
subtrees
on smallest
their
width,
it does
them.isProve
thatthat
thisisprocess
ends,the
andseparation
that
it ends
path.total
Write
aboundp:rogram
pointInPolygonQ[{{l,
O},
(0, 1),
{-l,this,
OJ, your
-l}}, {O,
leave
you
to discover
foryow-self,
except
to say
drnw
the
aryiscalledtheclfflvexhullofthesetofpoints.)Thatis,givenasetofpoints
in should
the
plane
atolevel-by-level
implement
this
comparison,
procedure
and
and then
separates
compare
them
the
paths
as{O,
far
given
asprogram
needed
byyOlU"
at0)]
function
any
panicular
with
•only
write
aof9.4:
function
convex
a graph
such
as the following .
Figure
Tm
Resultsfromdiff"renttree·drawingalgorjthms
tree
shown
in Figure
9.5 that
:roughly
asthe
you
see it
here.
those
simpleClosedPath
given
in
text.
level.
•outputs
•
• • • •
• •
'0'
•
'
"
1. Evaluate Play [Sin [lOOO/x] , {x, -2. 2} J. Explain the dynamics of the sound
generatedfromtWsfunction.
2. ExperimemVlith the Play function by creating arithmetic combinations of sin
functions. For example, you might try the following.
Sin[4402".tj
In{lJ;= Play
, {t, 0, 1}]
Sin[6602:rrt]
3.
OU/[I]= _Sound_
Create a tonethatdonhles in/i:eqllencyeachsecond.
4. Arquare wave consists of the addition of sine waves, each an odd multiple of a fundamental frequency; that is, it consists of the sum of sine waves having frequencies}O, 3
fo, 5[0, 7[0, etc. Create a square wave widl a fundamental frequency of 440 hertz. The
more overtones you include, the "squarer" the wave.
5". Create a square wave consisting of the sum of sine waves with frequencies /0, 3 jQ,
5fo, 7[0, etc., and amplimdes I,
etc. This is actually a truer square wave
than that produced in the previoul exercise.
6. Create a square vrave consisting of overtones that are randomly out of phase. How
does this wave differ from the previous two?
t, t, t,
7.
Astlwtooth w(f(!e
8.
A wide variety of sounds can be generated using FM ifruflU:ncy modulation) synthesis.
The basic idea ofFM synthesis is to use functions of the form
consists of the sum of both odd- and cven-numbercd overtones (fo, 2fo,
3fo,4fo, etc. with amplitudes in the ratios 1,
etc.) Create a sawtooth wave
and compare its tonal qualities with the square wave.
t,
+, i-,
a sin(2 11" F" t + mod sin(211" F" t))
where a is thc pcak amplitude, F, is the carrier frequ~ncy in hert~ mod is the modulation
index, and P", is dle modulating frequcncy in hertz.
Determine what effect varying the parameters has on the resulting tones by creating a
series ofFM synthesized tones. First, create a function FM [Amp, Fc, mod, Fm, time] that implements the above formula and generates a tone using the Play
function. Then you should try several examples to see what effect varying the parameters
has on the resulting tones. For example, you can e:enerate a tone "With strong vibrato at
a carrier frequency at middle A for one second by evaluating FM[l,44D,45,5,l].
10.
Modify
the routine
for generating
lUn music
so music
that frequencies
are chosen
9. Write
a function
pentatonic
that generates
liP
choosing notes
from aaccording to
a specifiedscale.
probability
distribntion.
Forbe
example,
youa might
usebeginning
the following
five-tone
A pentatonic
scale can
played on
piano hy
with C~,
distribution that indicates a note and its probability of being chosen; C-- 5%, C~and
then playing only the black
keys: q, Eb,
F~, Ab, q. The pentatonic
5%,D-5%,Eb-IO%,E-I0%,
F -lO%,F~-lO%,
G-lO%,Ab-IO%,A-IO%,
Bil - scale
5%, Bis- 5%,
C - 5%. (Hint:
TrytbeCeltic,
Whi<;h
function.)
common
to Chinese,
and
Native American mllsic.
11. Modify the routine for generating 1 I/0 music so that the duratiolls of the notes obey
l/fO scaling. Write a function tonesAndTimes tbat creates a two-dimensional list of
frequencies and time durations. Consider using the function MapThread.
[
12. If you read IDu.5ical notation, take a mnsical composition such as one of Bach's
Bmndmhurg Conce/Tos and write down a list of the frequency intervals x between
successive notes. Then find a function that interpolates the power spectrum of these
frequency intervals and determine if this function is of the form f(x) = c I x for some
constant c. (Hillt; To get the power spectrum, you will need to square the magnitude of
the Fourier transform: takeJ\bs [Fourier [ ... ] ] ~2 of your data.) Compute the power
spectra of different types of music using this procedure.
13. Modify the routine for genemting lIP music so that the duratious of the notes obey I/F
scaling.
14. Tbe follo'\ling series of exercises are designed to create Ilf music - music that i.5
mildly correlated.
a. Write a function Cmajor16 that extends Cmajorto 16consecutive.5emitones.
b. Write three functions red, green, and blue dlatsimnlate rolling 3 six-.5ided dice.
The first note from cmajor16 is picked by rolling the dice and choosing the note in
the position given by the sum (mod 16)+ I.
c. To generate the next eight notes, think of the numbers 0 through 7 in binary. Let red
correspond to the Is digit, green to the 2s digit, and blue to the 4£ digit.
StartingfromO,andgoingto I,onlythe Is digit changes. So only the rcd die is retossed,
the blue and green are left alone. This new sum (mod 16) of the red, green and blue is
the next position from the list Cmajor16. The third rail is obtained by noticing that ill
going from 1 to 2, both the Is digit and the 2s digit change. Hence, reroll the red and
green die, leaving the blue alone. The new sum of the three dice is the position of the
next note. Continue in this fasmon, rolling only those dice that correspond to digit
changes when moving through the numbers 0-7, base 2. Finally, generate the tones
corresponding to these frequencies.
d. Extend the above algorithm to include four dice to produce 16 notes from a l1-tone
scale. If you have a sufficiently powerful computer '\lith lots of memory and disk
space, try ten dice to produce 1,024notes from a 55-tone scale:
Download