Wednesday, November 12, 2014

NUmeric :Secant Method code

 

Sample equation for Secant Method

where X-1=3

and x0=4 ;

F(x)=2x3-11.7x2+17.7x1-5

//scant method
#include<stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
 
int main()
{
    float xi,Xii,newxi,Es,a[40],old=0,Ea;
    int n,K;
    cout<< "HIghest power in the equation : " ;
    cin>>n;
    //.........................................
    printf("Enter Xi =");
    scanf("%f",&xi);
    printf("Enter Xii =");
    scanf("%f",&Xii);
    printf("Enter Es =");
    scanf("%f",&Es);
    //..........................................
    printf("\n");
    printf("enter coefficient :\n");
    for (int i=n; i>=0; i--)
    {
        printf("X^%d =",i);
        scanf("%f",&a[i]);
    }
    //...........................................
    while(1)
    {
 
        float fxi=0,fXii=0;
//
       for (int i=n; i>=0; i--)
        {
             fxi=fxi+a[i]*pow(xi,i);
             fXii=fXii+a[i]*pow(Xii,i);
        }
 
        newxi=xi-((fxi*(Xii-xi))/(fXii-fxi));
 
 
//   printf("\n\n\nSTEP no: %d\n",K+1);
        printf("\nXi   =  %.2f",xi);
        printf("\nfxi  =  %.2f",fxi);
//
        printf("\nXii   =  %.2f",Xii);
        printf("\nfXii  =  %.2f",fXii);
//
        printf("\nnew Xi   =  %.2f",newxi);
//
        Ea=((newxi-old)/newxi)*100;
 
        old =newxi;
 
        //cout <<" now =" <<old;
        if(Ea<0)
        {
            Ea=Ea*(-1);
        }
        printf("\nEa= %f\n",Ea);
        if(Ea<Es)
        {
            break;
        }
        Xii=xi;
        xi=newxi;
 
        K++;
    }
    return 0;
}

No comments:

Post a Comment