Newton’s method pth root- MATLAB -
newton’s method can used calculate p-th root of positive real number. write matlab function myrootp.m calculates a^(1/p) a> 0 , positive integer p. function should stop when abs((xk^(p)/a)-1)<10^(-15).
i used following code cannot find error:
function root1 = root1( a,x0,p) xk=x0; fd= p*xk^(p-1); f=(xk^p)-a; if a<0 disp('error:a must positive , real') else k=1:p if abs(xk^p/a-1)<10^(-15) return disp('error'); else xk1=xk-f/fd; xk=xk1; fd= p*xk^(p-1); f=(xk^p)-a; end end end root1 = xk; return end
i'd point out unfamiliar algorithm finding nth root of number using newton's method.
back problem, there 2 errors:
- there no such keyword
then
in matlab. rid of it. - you'll want iterate until error specified. looping many times there power
p
, , it's highly possible algorithm can converge before then, or worst case require more iterationsp
converge.
making these 2 changes:
function root1 = root1(a,x0,p) xk=x0; fd= p*xk^(p-1); f=(xk^p)-a; if a<0 disp('error:a must positive , real') else while true if abs(xk^p/a-1)<10^(-15) break; else xk1=xk-f/fd; xk=xk1; fd= p*xk^(p-1); f=(xk^p)-a; end end end root1 = xk;
to test out, using initial guess of 5 or x0=5
, , want find square root of 10 (a = 10, p = 2
), get:
>> format long g; >> root1(10, 5, 2) ans = 3.16227766016838
comparing matlab's sqrt
function, get:
>> format long g; >> sqrt(10) ans = 3.16227766016838
Comments
Post a Comment