简体   繁体   中英

MatLab: iterative method for finding roots

i'm trying to implement a iterative method in order to find a root in matlab. This is my code, preatty simple

function [ res ] = iterative_method(f, a, b, x0, atol)

    prev = f(x0);
    xn = f(prev)
    while (abs(xn - prev) < atol)
       prev = xn
       xn = f(prev)

    end
    res = xn
end

Then, i want to find a root in the function

f(x) = x^3 - 30*x^2 + 2552

So i call my function

iterative_method(@(x) x^3 -30*x^2 + 2552,0,10,1,10^-4);

But the output makes no sense:

res =

   1.5869e+10

It does not work because of the algorithm you use, you are writting: x_{n+1} = f(x_n)

which is not an algorithm to find the root of a function.

EDIT: As it is written, your function iterative_method looks for the fixed points of function f and not its roots (ie it looks for points x such that x=f(x) and not such that f(x)=0). So if you want x such that f(x)=0, then you need to find a function g such that f(x)=0 writes g(x)=x, and apply your fixed point research on this function g and not f. In your particular case for instance,

x^3-30x^2+2552 = 0

could be written

x = sqrt((x^3+2552)/30) if you look for a positive root of function f, or x = -sqrt((x^3+2552)/30) for a negative one.

Therefore, you can apply your algorithm on function g: @(x) sqrt((x^3+2552)/30) (with modifying the stopping criterion as suggested by @Sardar_Usama), you will capture a positive root of f. Note however that the fixed point method is often not efficient since it needs conditions on the chosen function g to ensure convergence. You will find litterature about this subject on internet.

You have a lot of different algorithms available in the litterature (simplest link: wiki https://en.wikipedia.org/wiki/Root-finding_algorithm )

For your function I would suggest Newton's method which is very efficient (quadratic convergence) if you start near an existing root. For this you will need the derivative of the function and slightly modify your iterative_method function (also taking into account @Sardar_Usama comment, and get rid of a and b which are useless in your function):

function [ res ] = iterative_method(f,df, x0, atol)

prev = f(x0);
xn = f(prev)
while (abs(xn - prev) > atol)
   prev = xn
   xn = prev-f(prev)/df(prev)

end
res = xn
end

Then just call

iterative_method(@(x) x^3 -30*x^2 + 2552,@(x) 3*x^2-60*x,-10,10^-4);

This will find the closest root to -10, ie -8.1761...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM