13. Reprise:  Syntax and Data Types:  Homework

Last revision:  February 18 1998

Author: YourNameGoesHere

Precedence and Associativity

Show the complete order of evaluation (by placing parentheses everywhere necessary) of the following expression:

a = b = c = 2 - 2- 2 ^ 2 ^ 2

Machine-Precision Integers

Determine the range of possible machine-precision integers (both positive and negative) on a computer which devotes the following number of bits to integers.  (Expand your answer out, if necessary, to an integer; instead of answering "2^3", for instance, answer 8.)

(a) 32
(b) 16
(c) 8

Machine-Precision Approximations

Recall that function "N[]" forces the argument into a machine-precision approximation with a fixed number of digits.  Show that the numbers 1.2345678901234567890123 and 1.2345678901234567890124 are indistinguishable when converted to machine-precision. Hint:  convert each one, and then subtract.

Reading Code

Up to now we have often been writing code, not reading it, and the various pronouncements on style might easily go unappreciated.  Here we present several sections of code and ask you to determine what exactly the section of code performs.  One reasonable method to go about "deciphering" code is to read it over once, check some input and output, and then delve into one function at a time.  If the functions have usage lines, all the better; if not, you will have to consider how they work solely from the function definitions inside.  As you work through function by function, consider if any variables are local or global, if modules have side effects, and be careful unravelling anonymous functions!  Make sure to comment on style, local and global variables, readability, comments, and usage lines.

(a) split

Clear[split]
split[a_,b_] := Module[
		  {low=If[a>b,b,a], high=If[a>b,a,b],flip=0},
		  makemid[x_,y_] := N[(x+y)/2];
		  absval[x_] := If[x>0,x,-x];
		  While[absval[high-low]>0.001,
				  If[flip==0, (* check flip *)
				   (high=makemid[low,high]; flip=1),
				   (low=makemid[low,high]; flip=0)
				  ]
		  ];
		  {low,high} (* output low and high *)
		]

(b) everyOtherPrime

Clear[everyOtherPrime]
everyOtherPrime[n_Integer] := 
  Module[{facs},
    facs=FactorInteger[n];
    facs=Map[(First[#])&,Partition[facs,2]];
    facs
  ]
everyOtherPrime::usage="everyOtherPrime[n] decomposes an Integer n into its prime factors and returns a list of pairs {p1,p2} where p1 is a prime and p2 is the power of the prime in the Integer n.  Note that everyOtherPrime skips every other prime in the decomposition.";

(c) myFun

Clear[myFun]
myFun[s_String?((StringLength[#]>5)&),a_Integer:1] :=
	 Module[ {wonderful,amazing},
	   wonderful=Map[ToCharacterCode,Characters[s]];
	   amazing=Map[Last,Partition[Sort[wonderful],a]];
	   incredible=Join[Map[FromCharacterCode,amazing]];
	   incredible
	 ];