matrix - How to solve n equation with Jacobi method by C++? -
this code should get
- number of equations (n)
- matrix a
- matrix b
- accuracy of answer (e)as input
and find answer of n equations jacobi method.
my code:
#include <cstdlib> #include <iostream> #include <conio.h> #include <math.h> using namespace std; // dev software code using 'cin' instead 'scanf' int main() { int n,i,j,l=0; cout<<"enter number of equations = "; cin>>n; double a[n-1][n-1],b[n-1][1],x[n-1][1],t[n-1][1],e,k; cout<<"[a].[x]=[b]"<<endl; cout<<"enter matrix a:"<<endl; for(i=0;i<n;i++) for(j=0;j<n;j++) { cout<<"a["<<i<<","<<j<<"] = "; cin>>a[i][j]; } cout<<"enter matrix b:"<<endl; for(j=0;j<n;j++) { cout<<"b[0,"<<j<<"] = "; cin>>b[0][j]; } cout<<"enter accuracy = "; cin>>e; (i=0;i<n;i++) t[i][0]=0; while (l!=n) { l=0; (i=0;i<n;i++) { x[i][0]=(1/a[i][i])*(b[i][0]); (j=0;j<n;j++) { if (j!=i) x[i][0]=x[i][0]-(1/a[i][i])*(a[i][j]*t[j][0]); } } for(i=0;i<n;i++) { k=fabs(x[i][0]-t[i][0]); if (k<=e) { l=l+1; } } (i=0;i<n;i++) t[i][0]=x[i][0]; } (i=0;i<n;i++) cout<<"x"<<i+1<<"="<<x[i][0]<<endl; getch(); return 0; }
for example: (e.g.)
// initializing variables n=2 e=0.001 a[0,0]=4 a[0,1]=2 a[1,0]=1 a[1,1]=3 b[0,0]=1 b[1,0]=-1
the answer should x1=0.5
, x2=-0.5
. output of code x1=0.35
, x2=-0.45
.
what's problem?
regards
your arrays they're short 1 row , 1 column. ask user n
equations, allocate n-1
rows , columns a, b, x, t
. declarations matricies , vectors should double a[n][n]
, etc. you're writing outside bounds of arrays , possibly overwriting data in matrix.
by way, got right answer (0.5, -0.5) when applied fix.
Comments
Post a Comment