Wednesday, September 28, 2016

solving linear equation by matrix normalization method

#include<bits/stdc++.h>

using namespace std;

int main()
{
    int a[4],b[4],c[4],e[4];

    char buff[10];

    string str;

    int m=1,n=1,l=1,k=1,h=0,d=0;
    int flag=0;

    for(int i=0; i<3; i++)
    {
        getline(cin,str);

        d=0,flag=0;

        for(int j=0; j<str.size(); j++)
        {
            if(str[j]=='-') flag=1;

            else if(str[j]>='0' and str[j]<='9') buff[d++]=str[j];

            else if(str[j]=='=' or str[j]=='+' or str[j]==' ') continue;

            else if(str[j]=='x')
            {
                buff[d++]=NULL;

                h=atoi(buff);

                if(h==0) h=1;
                if(flag==1) h=-h;

                a[m++]=h;

                memset(buff,NULL,sizeof(buff));
                d=0;
                flag=0;

            }
            else if(str[j]=='y')
            {
                buff[d++]=NULL;

                h=atoi(buff);

                if(h==0) h=1;
                if(flag==1) h=-h;

                b[n++]=h;

                memset(buff,NULL,sizeof(buff));
                d=0;
                flag=0;

            }
            else if(str[j]=='z')
            {
                buff[d++]=NULL;

                h=atoi(buff);

                if(h==0) h=1;
                if(flag==1) h=-h;

                c[l++]=h;

                memset(buff,NULL,sizeof(buff));
                d=0;
                flag=0;
            }

        }
        buff[d++]=NULL;
        h=atoi(buff);


        if(flag==1) h=-h;

        e[k++]=h;

        memset(buff,NULL,sizeof(buff));
        d=0;
        flag=0;
    }

    double a11,a12,a13,a21,a22,a23,a31,a32,a33,x1,x2,x3,c1,c2,c3,y1,y2,y3;

    a11=a[1],a21=a[2],a31=a[3];
    a12=b[1],a22=b[2],a32=b[3];
    a13=c[1],a23=c[2],a33=c[3];

    c1=e[1],c2=e[2],c3=e[3];


    double l21,l31,l32,u11,u12,u13,u22,u23,u33;

    u11=a11;
    u12=a12;
    u13=a13;

    l21=a21/u11;

    u22=a22-(l21*u12);

    u23=a23-(l21*u13);

    l31=a31/u11;

    l32=(a32-(l31*u12))/u22;

    u33=a33-(l31*u13)-(l32*u23);

    y1=c1;

    y2=c2-(l21*y1);

    y3=c3-(l31*y1)-(l32*y2);

    x3=(y3/u33);

    x2=(y2-(u23*x3))/u22;

    x1=(y1-((u12*x2)+(u13*x3)))/u11;

    cout<<x1<<endl<<x2<<endl<<x3;
}

No comments:

Post a Comment