## Iteration of a formula

Asked by Sam Thorpe

### Sam Thorpe (view profile)

on 28 Feb 2019
Latest activity Commented on by Sam Thorpe

### Sam Thorpe (view profile)

on 1 Mar 2019
Accepted Answer by Yasasvi Harish Kumar

### Yasasvi Harish Kumar (view profile)

I have the following function y=4*(1-cos(x)).^2+x.^3. Using newtonian iteration how can iterate the formula 100 times with initial guess of x=4?
I have the following code so far which gets me the first root, but im not sure how to progress from here.
maxIter=100'; %number of iterations
x=4; %initial guess
i=0;
f=4*(1-cos(x)).^2+x.^3 %function
dfx=3*x.^2+8*sin(x)*(1-cos(x)) %derivative of function
y=x-(f/dfx)
newx=y
x=newx
i=i+1
Thanks for any help

### Tags

Answer by Yasasvi Harish Kumar

### Yasasvi Harish Kumar (view profile)

on 1 Mar 2019

Hi,
All you need is a loop. This should fix your problem.
maxIter=100'; %number of iterations
i = 1;
x(i)=4; %initial guess
while i<=maxIter
f=4*(1-cos(x(i))).^2+x.^3 %function
dfx=3*x(i)^2+8*sin(x(i))*(1-cos(x(i))) %derivative of function
y=x(i)-(f/dfx)
i=i+1
x(i) = y;
end
x is an array with all the roots.
Regards

Sam Thorpe

### Sam Thorpe (view profile)

on 1 Mar 2019
thanks a lot yasasvi. that is brilliant.