Secant Method

Metamug
Secant Method

Introduction

Finding roots of an equation is important in solving problems. In programming, numerical methods are used to find the roots. One of the popular method of root finding is secant method.

Formula

In each iteration, we compute the next value.

Secant method

The above formula translates to

x2 = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0))

We reassign the variables and compute the next iteration.

x0 =  x1;
x1 =  x2;   

Breaking the loop

So there are two ways, either we can define the fixed iterations, so we know beforehand the number of iterations or we check the difference between the last two x values.

if(Math.abs(x2 - x1) < 0.1f) break; // x1 and x2 are very close 

If the two values are close to each other, then we can break the loop as we do not require further iterations.

Code

def secant_method(f, x0, x1){
    int n = 0; float x2 = 0.0f;
    // Return the root calculated using the secant method.
    while(true){
        x2 = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0))
        if(Math.abs(x2 - x1) < 0.000001f) break; // x1 and x2 are very close 
        x0 =  x1;
        x1 =  x2;   
        println "iteration:"+ n++
    }

    return x2
}
def f_example = { x  ->
    return f =  x**2 + 2*x + 1;
}

root = secant_method(f_example, -10, 10)
println root.round(6);

In groovy, if x2 is not defined explicity as float. If not, it will lead to computation of BigDecimal by default.

Complex roots

The above method will not work for complex roots sqrt(-1). For example, f = x**2 + 1 will consume a lot of iteratios and will not produce any value.

Reference

Secant method. (2022, November 14). In Wikipedia. https://en.wikipedia.org/wiki/Secant_method



Icon For Arrow-up
Comments

Post a comment