I'm very, very new to R, and my instructor's example seemed like a special case (or I just don't know how to extrapolate his syntax to my problem).
Here's the example we used: Approximate the square root of $a=12345$. So we used the function $f(x)=x^2-a$ and approximated the (positive) root with this code:
sq<-function(a){
a=12345
x=a/2
while(abs(x^2-a)>.00001){
x=((x+a)/x)/2
}
}
sq(a)
This might not be entirely accurate, I've made the silly mistake of making changes and saving >_< But I hope it's enough to get the gist.
Assuming this code works, I've been trying to expand on this template to apply it to my case, which is to find the roots of $g(x)=x^3+4x^2-10$ with an initial guess of $1.5$.
As near as I can tell, in the example, $x=\dfrac{a}{2}$ was the initial guess. I don't really know what to do with the $a$.
Here's the code I've attempted to write:
root<-function( ??? ){
x=1.5
while(abs(x^3+4*x^2-10)>.00001){
x=x-(x^3+4*x^2-10)/(3*x^2-8*x)
}
}
root( ??? )
The "???" are used to mean I've left the arguments blank and have no idea what to use.
You can pass in the function, its derivative, an initial guess, and your desired tolerance to the
rootfunction as arguments:This outputs: