Professional Documents
Culture Documents
Deepak Sela 4/16/2015 Ratnaswamy 1) : While
Deepak Sela 4/16/2015 Ratnaswamy 1) : While
4/16/2015
Ratnaswamy
1)
x = 1;
Tol = 0.0000001;
count = 0;
dx=1;
%this is a fake value so that the while loop will execute
f=-1;
% because f(-2)=-13
fprintf('step
x
dx
f(x)\n')
fprintf('---- ----------- ------------------\n')
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
xVec=x;fVec=f;
while (dx > Tol || abs(f)>Tol) %note that dx and f need to be defined for
this statement to proceed
count = count + 1;
fprime = 3*x^2 - 2;
xnew = x - (f/fprime);
% compute the new value of x
dx=abs(x-xnew);
% compute how much x has changed since last step
x = xnew;
f = x^3 - 2*x;
% compute the new value of f(x)
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
end
x = -1;
Tol = 0.0000001;
count = 0;
dx=1;
%this is a fake value so that the while loop will execute
f=-3;
% because f(-2)=-13
fprintf('step
x
dx
f(x)\n')
fprintf('---- ----------- ------------------\n')
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
xVec=x;fVec=f;
while (dx > Tol || abs(f)>Tol) %note that dx and f need to be defined for
this statement to proceed
count = count + 1;
fprime = 3*x^2 - 2;
xnew = x - (f/fprime);
% compute the new value of x
dx=abs(x-xnew);
% compute how much x has changed since last step
x = xnew;
f = x^3 - 2*x;
% compute the new value of f(x)
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
end
X = -1
>> newton2
step
dx
f(x)
----------
X=1
>> newton2
step
dx
f(x)
----------
An initial guess of 0 will invalidate the function, which has no constant, and
that will lead to few iterations. The program only recognizes the numbers that
are inputted for the x and f value; if zero, the program will only return outputs
(as seen below).
X=0
>> newton2
step
x
dx
f(x)
---- ----------- --------- ---------0 0.00000000 1.00000000 0.00000000
1 0.00000000 0.00000000 0.00000000
2)
x = 0;
Tol = 0.0000001;
count = 0;
dx=1;
%this is a fake value so that the while loop will execute
f=1;
% because f(-2)=-13
fprintf('step
x
dx
f(x)\n')
fprintf('---- ----------- ------------------\n')
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
xVec=x;fVec=f;
while (dx > Tol || abs(f)>Tol) %note that dx and f need to be defined for
this statement to proceed
count = count + 1;
fprime = sin(x) - 3;
xnew = x - (f/fprime);
% compute the new value of x
dx=abs(x-xnew);
% compute how much x has changed since last step
x = xnew;
f = cos(x)-3*x;
% compute the new value of f(x)
fprintf('%3i %12.8f %12.8f %12.8f\n',count,x,dx,f)
end
>> newton2
step
dx
f(x)
----------