Thursday, March 1, 2007

How to Design Programs - 2.1 Numbers and Arithmetic

Here are the exercises and my solotions of Section 2.1, called "Numbers and Arithmetic", in How to Design Programs.

Exercise 2.1.1.

Find out whether DrScheme has operations for squaring a number; for computing the sine of an angle; and for determining the maximum of two numbers.

Solution:

In the Help Desk, Manuals, Beginning Student Language, there are these entries:

sqr : (num -> num)

purpose:
to compute the square of a number

sin : (num -> num)

purpose:
to compute the sine of a number (radians)

pi : real

purpose:
the ratio of a circle's circumference to its diameter

max : (real real ... -> real)

purpose:
to determine the largest number

Now, this would mean the following:

(define (square n)
  (sqr n))

(define (sin-angle a)
  (sin (* (* 2 pi) (/ a 360))))

(define (maximum n1 n2)
  (max n1 n2))

Running this code gives the following output:

> (square 5)
25
> (sin-angle 90)
#i1.0
> (sin (/ pi 2))
#i1.0
> (sin-angle 180)
#i1.2246467991473532e-16
> (sin pi)
#i1.2246467991473532e-16
> (maximum 3 5)
5
> (maximum -3 -5)
-3

So, there is the primitive sqr to calculate the square of a number, you need to use a formula with pi to convert from angles to radian, and there is the primitive max to calculate the maximum of two numbers.

Exercise 2.1.2.

Evaluate (sqrt 4), (sqrt 2), and (sqrt -1) in DrScheme. Then, find out whether DrScheme knows an operation for determining the tangent of an angle.

Solution:

> (sqrt 4)
2
> (sqrt 2)
#i1.4142135623730951
> (sqrt -1)
0+1i
> (tan (* (* 2 pi) (/ 45 360)))
#i0.9999999999999999

No comments: