C++ program for Gauss Elimination method to finding solutions to simultaneous linear equation in n variable.
#include<iostream> #include<fstream> using std::cin; using std::cout; using std::endl; //make a1 -> a2 double factor(double a1,double a2){ return (a2/a1); } void prog(){ int var; cout<<"Enter number of variables/number of equations : "; cin>>var; cout<<"Enter equations \na1x+b1x=z1\na2x+b2x=z2 \n -- in the form -- \n a1 b1 z1 \n a2 b2 z2\n "; double arr[var+1][var+2]; for(int i=1;i<=var;i++){ for(int j=1;j<=var+1;j++){ cin>>arr[i][j]; } } int elem=1; //converting to upper triangular form for(int i=1 ;i<var; i++){ for(int j=i+1; j<=var; j++){ if(arr[j][elem]==0) continue; double rat=factor(arr[i][elem],arr[j][elem]); for(int k=elem; k<=(var+1); k++){ arr[j][k]=arr[j][k]-arr[i][k]*rat; } } elem++; } //back substitution double ans[100] = {0}; int skip=var; for(int i=var;i>0;i--){ double temp_ans=arr[i][var+1]; for(int j=i;j<=var;j++){ if(j==skip) continue; temp_ans-=ans[j]*arr[i][j]; } if(arr[i][skip]!=0) ans[skip]=temp_ans/arr[i][skip]; else ans[skip]=0; skip--; } cout<<endl; for(int i=1;i<=var;i++){ cout<<"variable "<<i<<" = "<<ans[i]<<endl; } } int main(){ //freopen("inps.txt","r",stdin); prog(); }
No comments:
Post a Comment
Share your thoughts