You are on page 1of 4

Bohol Island State University – Main Campus

College of Engineering and Architecture


Undergraduate Program

SECANT METHOD USING C++

Submitted to
Engr. Sime Camanse
Instructor
Rachelle Mae C. Tomo
BSCE 3A

I. Introduction

In numerical analysis, the secant method is a root-finding algorithm that uses a succession of roots of
secant lines to better approximate a root of a function f. The secant method can be thought of as a
finite-difference approximation of Newton's method. However, the secant method predates Newton's
method by over 3000 years.

The secant method does not require that the root remain bracketed, like the bisection method does,
and hence it does not always

II. Problem Statement

Use any programming tool (Microsoft Excel, Matlab, Python, etc.) to locate the root of f(x) =
Ax^4+Bx^3+Cx^2 + Dx + E

III. Methodology / Algorithm

Step 1: Choose i=1

Step 2: Start with the lower and upper limit, xi-1 and xi

Step 3: Use the formula

Step 4: Find Absolute Error,|Ea|= |(Xi+1 -Xi)/Xi+1|*100

            Check if |Ea| <= Es (Prescribed tolerance)

            If true then stop

IV. Algorithm Flow Chart

V. Programming Using C++ Program for secant method

#include<iostream>

#include<iomanip>
/* 'cmath' header file is included for pow and fabs functions */

#include<cmath>

using namespace std;

double secant_method(double ,double ,double ,int* );

double f(double );

int main()

double x0,x1,e;

int iteration_no=0;

cout<<"\nEnter lower limit: ";

cin>>x0;

cout<<"\nEnter upper limit: ";

cin>>x1;

/* it should as low as possible, like 0.001 or 0.0001 */

cout<<"\nEnter tolerance: ";

cin>>e;

cout<<"i"<<setw(16)<<"x0"<<setw(12)<<"x1"<<setw(18)<<"xm0"<<setw(18)<<"f2"<<endl;

double res=secant_method(x0, x1, e, &iteration_no);

cout<<"\nRoot of the given equation is "<<res;

cout<<"\nNo. of iterations are "<<iteration_no;

return 0;

double secant_method(double x0, double x1, double e, int* iteration_no)

double xm0,xm1,k,f1,f2;

do

cout<<*iteration_no<<setw(16)<<x0<<setw(12)<<x1<<setw(18)<<xm0<<setw(18)<<f2<<endl;

/* calulating and storing values of f(x1) and f(x2) into f1 and f2 resp */
f1=f(x0);

f2=f(x1);

/* updating iteration number */

*iteration_no+=1;

/* calculating the intermediate value */

xm0 = (x0 * f2 - x1 * f1) / (f2 - f1);

/* checking wheather xm1 is root of the equation or not */

k = f(x0) * f(xm0);

/* updating the value of intervals */

x0 = x1;

x1 = xm0;

/* if xm1 is the root of equation then break the loop */

if (k == 0)

break;

xm1 = (x0 * f2 - x1 * f1) / (f2 - f1);

}while( fabs(xm1 - xm0) >= e); /* check if the error is greater than the desired accuracy. fabs function is
used to return non-negative float value of its argument */

return xm0;

double f(double no)

/* write the equation whose roots are to be determined. Here we are using equation as x^3 + x - 1 */

double res = pow(no, 3) + no - 1;

return res;

You might also like