Simple code for Secant Method
7 views (last 30 days)
Show older comments
I was asked to write a simple code for the Secant Method and display results in a table showing Pn, Pn - P* and a few other things. I am trying to get it to solve y = x^2-2. For some reason I can't get my code to perform more than one iteration even though I reassign the variable at the end. Here is my code, and the result I am getting. I need to go to n = 10.
function SecantProject
disp('*******************************')
p0 = 1; p1 = 2; TOL = 0.000001;
for i = 2:10
q0 = f(p0);
q1 = f(p1);
p = p1 - q1(p1-p0)/(q1-q0);
Err = p - sqrt(2);
Alpha0 = abs(p - sqrt(2))/(p0-sqrt(2))^1;
Alpha1 = abs(p - sqrt(2))/(p0-sqrt(2))^1.618;
Alpha2 = abs(p - sqrt(2))/(p0-sqrt(2))^2;
if abs(p-p1)< TOL
q = f(p);
q*q1 < 0;
p0 = p1;
p1 = p;
end
end
fprintf('P0 = %f\n\n', p0)
fprintf('Pn \t\t\t\t Pn-Sqrt(2)\t\t Alpha = 1\t\t Alpha = 1.618\t Alpha = 2\n'); fprintf('__________________________________________________________________________\n')
fprintf('%f \t\t %f\t\t %f\t\t %f\t\t %f\t\t\n', p, Err, Alpha0, Alpha1, Alpha2);
function y = f(x)
y = x^2 - 2;
end
end
And this is the result:
SecantProject
*****************************
P0 = 1.000000
Pn Pn-Sqrt(2) Alpha = 1 Alpha = 1.618 Alpha = 2 ________________________________________________________________________
1.333333 -0.080880 -0.195262 0.12
The formatting looks off on here, but I just need to know how to continue for 8 more iterations?
0 Comments
Answers (0)
See Also
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!