How to solve function with Bisection and Secant method

29 Ansichten (letzte 30 Tage)
AlyseW7
AlyseW7 am 19 Feb. 2016
Beantwortet: Kinza Shahzad am 1 Jun. 2018
Hi, I need help solving the function 600x^4-550x^3+200x^2-20x-1=0 using the Bisection and Secant method in MATLAB. I tried using a previous code for the bisection method but had no luck.
function p = Bisection(f,a,b)
% Provide the equation you want to solve with R.H.S = 0 form.
f = 600*p^4-550*p^3+200*p^2-20*p-1;
% Write the L.H.S by using inline function
% Give initial guesses.
a=1;
b=2;
% Solves it by method of bisection.
if f(a)*f(b)>0
disp('Choose another guess')
else
p = (a + b)/2;
err = abs(f(p));
while err > 1e-7
if f(a)*f(p)<0
b = p;
else
a = p;
end
p = (a + b)/2;
err = abs(f(p));
end
end
For the Secant method, I tried implementing the code used on a Wikipedia site but also am having trouble.
%Secant Method is used to find a solution to f(x)=0
%Reference: https://en.wikipedia.org/wiki/Secant_method
f=@(x) 600*x^4-550*x^3+200*x^2-20*x-1;
x(1)=0.1;
x(2)=1;
for i=1:10
x(i) = x(i-1) - (f(x(i-1)))*((x(i-1) - x(i-2))/(f(x(i-1)) - f(x(i-2))));
end
root=x(10)
I am not used to using MATLAB and would really like some advice on how to solve these problems.

Antworten (2)

Arnab Sen
Arnab Sen am 24 Feb. 2016
Hello AlyseW7,
I have investigated on both code for Bisection and secant methods and have few observations, which I will discuss one after another:
1. Bisection method:
I. You need to define 'f' as anonymous function and 'f' should hold the handle of the function as below:
>> f = @(p)600*p^4-550*p^3+200*p^2-20*p-1;
II. The initial guess is not accurate. If we have a closer look into the function 'f' we can easily notice there are very limited set of values for which it will evaluated to be negative. Because we can see that (600*p^4-550*p^3) is positive for any p>=1 and p<0. Similar is the case for (200*p^2-20*p). for p=0, f(p)=-1. So, clearly the solution is something between 0 and 1. Hence we can choose the initial guess wisely as a=0 and b=1. This should give the solution as 0.2324.
2. Secant Method:
I. I notice an error in the line # 7 of the code, i.e evaluation of 'x(i)' inside the for loop. Unlike other languages C or C++ MATLAB array indexing starts from 1 instead of 0. Now for i=1, x(i-1) is evaluated as x(-1) and x(i-2) evaluated as x(-2), where negative subscript in array is not allowed. So, start the loop for i=3 to avoid it as below
for i=3:10
x(i) = x(i-1) - (f(x(i-1)))*((x(i-1) - x(i-2))/(f(x(i-1)) - f(x(i-2))));
end
Regards,
Arnab

Kinza Shahzad
Kinza Shahzad am 1 Jun. 2018
but this one is not accurate for 5 decimal places :/ , what to do for that ?

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Noch keine Tags eingegeben.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by