Writing a square root function in R
<p>I'm trying to write a square root function in R. The function is supposed to behave like sqrt() but not use that function of course. I'm supposed to use Newton's method for computing the square root, which is:</p>

<p>y(a+1) = [y(a) + x / y(a)]/2</p>

<p>Here x is the number I'm trying to calculate the square root of and y(0) would be the initial guess of the square root of x.</p>

<p>The function is supposed to take in four arguments: x (the number I'm trying to compute the square root of), eps (the difference in value between iterations that are considered be equal), iter (the max number of iterations), and verbose (says I want to output intermediate results).</p>

<p>My issue is that I am not very well versed in writing functions in R. I have experience in C++, but they are slightly different in R. </p>

<p>I believe I'm supposed to write something that goes like this.</p>

<p>Asks the user to input a number as a guess for the value we want to calculate the square root of. Make a for loop from 1 to iter with two if statements 1) that stop the function and output the y value if the max number of iterations have been reached 2) stop the function and output the y value if the difference between successive iterations is less than eps. </p>

<p>Here is the code I have so far:</p>

<pre><code>MySqrt &lt;- function (x, eps = 1e-6, iter = 100, verbose = TRUE) {
 for (i in 0:itmax) {
   y[0] &lt;- readline(prompt="Please enter your initial square root      guess: ")
   y[i + 1] = (y[i] + x / y[i])/2
   if (i == 100) {
     stop (return(y[i + 1]))
   }
   if (abs(y[i + 1] - y[i]) &lt; eps) {
     stop (return(y[i + 1]))
   }
}
return(y[i + 1])
}
</code></pre>

<p>Here is the error I receive after entering the initial square root guess: Error in y[0] &lt;- readline(prompt = "Please enter your initial square root guess: ") : 
  object 'y' not found</p>

<p>Honestly, I didn't expect the code to work because I'm sure there are more than one errors.</p>