--[[ Square Root by Newton's Method Functional Programming Example H. Conrad Cunningham, Professor Computer and Information Science University of Mississippi Developed for CSci 658, Software Language Engineering, Fall 2013 1234567890123456789012345678901234567890123456789012345678901234567890 2013-09-08: Completed prototype This square root function is adapted from section 1.1.7 of Abelson and Sussman's Structure and Interpretation of Computer Programs (SICP) textbook. --]] -- Function "sqrt" computes the square root of its argument "x" using -- Newton's method. local function sqrt(x) local function square(x) return x * x end local function good_enough(guess,x) return math.abs(square(guess)- x) < 0.001 end local function average(x,y) return (x + y) / 2 end local function improve(guess,x) return average(guess,x/guess) end local function sqrt_iter(guess,x) if good_enough(guess,x) then return guess else return sqrt_iter(improve(guess,x),x) end end if type(x) == "number" and x >= 0 then return sqrt_iter(1,x) else error("Square root cannot be computed for " .. tostring(x), 2) end end -- Testing of sqrt local testvals = {0,1,2,3,4,5,6,7,8,9,10,16,25,36, 49,64,81,99,100,1000,10000} print("\nSquare Root") for _, v in ipairs(testvals) do print("sqrt(" .. tostring(v) .. ") = " .. tostring(sqrt(v))) end