Assignment 1 Solution



Please do all three questions using the LearnOCaml system as explained in class. There is a fourth question which you don’t have to do or even look at. This is a so-called \spiritual growth” question. It will not earn you any extra credit for the course.

Q1. [30 points] Here is a way to compute the square root of a positive real number say x. We make a wild guess that the square root is some number g. Then we check if g2 is close to x. If it is we return g as our answer; if not we re ne our guess using the formula

g0 = (g + x=g)=2:0

where g0 is the new guess. We keep repeating until we are close enough. Write an OCaml program to implement this idea. Since we are working with oating point numbers we cannot check for equality; we need to check if the numbers are close enough. I have written a function called close for you as well as a function called square. In OCaml oating point operations need special symbols: you need to put a dot after the operation. Thus you need to write, for example, 2:0 + :3:0. All the basic arithmetic operations have dotted versions: +:; :; =: and must be used with oating point numbers. You cannot write expressions like 2 + :3:5 or 2:0 + 3:0. We will not test your program on negative inputs so we are not requiring you to deal with the possibility that you may get a negative answer. There are of course built-in functions to compute square roots. We have written the tester program to check if you used this; you will get a zero if you use a built-in function.

Q2. [30 points] This is similar to the question above except that we are computing cube roots. The formula to re ne the guess is

g0 = (2:0 g + x=g2)=3:0

where I am using mathematical notation with arithmetic operation symbols overloaded. In your code you must use the oating-point versions of the arithmetic operations.

Q3. [40 points] In lecture 1 I quickly explained the Russian peasant algorithm for fast exponentia-tion. In this exercise you have to implement a tail-recursive version of the algorithm. Everything is with integers in this question so please do not use oating point operations. Our tester will detect whether you used built-in functions, so please don’t try to use them.


Q4. [0 points] This question is for your spiritual growth only. Do not think it will give you extra credit or help you learn the material better. It will however stretch your brain in other directions. Do not attempt it if you have not yet nished the required homework. Do not submit a solution; please talk to me if you have solved it. Do not worry about it if you don’t understand the question.

Why do the algorithms for square root and cube root above converge? Will this kind of idea work for any function? What is the correct update formula for fth roots?