Search code examples
matlabrootnumericalscientific-computing

Developing a Secant Method Program for root finding


So I have been trying to develop a secant method program that can be used for finding the root of

f(x) = tanh(x) - (x / 3)

However the answer output is nowhere close. Every solution I have found seems a more complex way to solve it.

    x = 2;
prevx = x;

for i = 1:20

    x = x - (tanh(x)-(x/3))*((x-(prevx))/((tanh(x)-(x/3))-(tanh(prevx))-((prevx/3))));
    prevx = prevx + x;
    x
end

The answer should be 2.987. I am getting a negative number though for some reason.


Solution

  • You suppose to add up terms so replace minus in this line:

    x = x - (tanh(x)-(x/3))*((x-(prevx))/((tanh(x)-(x/3))-(tanh(prevx))-((prevx/3))));
    

    To a plus:

    x = x + (tanh(x)-(x/3))*((x-(prevx))/((tanh(x)-(x/3))-(tanh(prevx))-((prevx/3))));
    

    To get a desired result of 2.987 for x. Also remove x before the end of the loop.