I am trying to construct a program that will find the square root of a number, using Newton's method, which is
$$x(n+1) = x_n- f(x) / f'(x_n)$$
The number, will be a random number, generated by: RandomInteger[{1000000, 10000000}]
I am setting the first Newton estimate to be 1, so I can iterate my loop until the difference in the estimate from Newton's method after n iterations to the first estimate of 1, being less than 0.001. Since I am trying to construct this fully, I am not using any Sqrt[x]
function or $n^.5$ relationship either.
My current thoughts:
So I have set:
f[x]:=x^2 + k
where
k = RandomInteger[{1000000, 10000000}]
Since I want to know what number I am taking the SQRT of, I am Printing that information out with:
Print["The Square Root of ", k, " is ", ---]
where --- will be my program.
Since I need to take an unknown number of iterations, I am thinking of using a For
loop, as that checks the loop invariant condition until it is False
then stops. This is the part I am stuck on -- what I can't grasp: how do I make the loop check for a condition that is outside of the loop?
Any help or hints would be greatly appreciated.
f
: what does this have to do with your question? In order to findx
for whichx^2 == k
, you want equivalentlyx^2 - k == 0
, so the function to iterate isf[x_] := x^2 - k
. (And you have the syntax for definingf
wrong: you missed the pattern character_
in the left-hand side.) $\endgroup$For
loop? You can just useNest
orNestWhile
, or if you want to see all the iterates,NestList
orNestWhileList
. Or is this homework exercise where somebody is forcing you to use explicitly aFor
loop? If so, you cannot expect us to do your homework for you; at the very least you need to show us the code you already have for the iteration withFor
. $\endgroup$NestWhile
. Unless your aim really is to use only those three looping functions, could you please edit your question to be less specific about which functions to use? $\endgroup$Nest
shows how to perform a fixed number of Newton-Raphson iterations to find $\sqrt{2}$. UseNestWhile
, as suggested by @Murray, to make this more flexible.NestWhileList
will return the intermediate results. $\endgroup$