#newton iteration for finding sqrt(2) #parameters x = starting value # error = error tolerance in the approximation #usage newtonWhile(3.1, 0.00001) #to get more digits use options(digits=15) newtonWhile = function(x, error){ #function body start #do the first iteration, compute error x1 = 0.5*(x + 2/x) delta = abs( x1 - x ) cat( "first delta = " , delta , "\n") x = x1 while (delta > error){ #while starts oldx = x x = 0.5*(x + 2/x) delta = abs( x - oldx ) } #while ends print(x) cat( "last delta = " , delta , "\n") } #funtion body ends