Ok, so first we made a very hard-coded sqrt, then we improved it by adding the concept of fixed points, which made the algorithm easier to see in the code. Here’s how we can improve it even further. Go to 32:30 in this video (stop at the break at 43:00):
First we define an average-damp function. This function takes a function as its argument and returns another function which takes a number and returns the average of that number and result of calling the function argument on the number. It’s easier to say that in clojure:
(defn average-damp [f]
(fn [x] (average x (f x))))
f is a function, average-damp creates a new function that takes x (a number) and that new function averages x and f(x).
Now that I have that, I define sqrt like this (you can find average and fixed-point in yesterday’s post):
(defn sqrt [x] (fixed-point (average-damp (fn [y] (/ x y))) 1))
Tomorrow, we’ll use this to implement another way of finding sqrt.