Gaussian Elimination program

This is a discussion on Gaussian Elimination program within the C++ Programming forums, part of the General Programming Boards category; I'm not sure what's wrong, i get the wrong the answers for x, i should be getting: x0=1 x1=-1 x2=1 ...

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    4

    Gaussian Elimination program

    I'm not sure what's wrong, i get the wrong the answers for x, i should be getting:
    x0=1
    x1=-1
    x2=1

    Code:
    int main()
    {
    
    	int n = 3, i = 0, j = 0, k = 0;
    	double m = 0;
    
    	double *b;
    	b = new double[n];
    	b[0]=0; b[1]=3; b[2]=2;
    
    	double *x;
    	x = new double[n];
    	double **A;
    	A = new double *[n];
    	for(int i=0; i<n; i++)
    		A[i] = new double [n];
    	A[0][0]=1; A[0][1]=2; A[0][2]=1; 
    	A[1][0]=2; A[1][1]=2; A[1][2]=3; 
    	A[2][0]=-1; A[2][1]=-3; A[2][2]=0;
    
    	for (int k=0; k<=n-2; k++)
    	{
    		for (int i=k+1; i<=n-1;i++)
    		{
    			double m = A[i][j]/A[k][k];
    			for (int j=k; j<=n-1; j++)
    				A[i][j] = A[i][j] - m*A[k][j];
    			b[i] = b[i] - m*b[k];
    		}
    	}
    	x[n-1] = b[n-1]/A[n-1][n-1];
    	for (k=n-2; k>=0; k--)
    	{
    		x[k]=0;
    		for (j=k+1; j<=n-1; j++)
    			x[k] = x[k] + A[k][j] * x[j];
    		x[k] = (b[k] - x[k])/A[k][k];
    	}
    	cout << x[1];
    	system ("pause");
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,624
    You've probably confused yourself by having multiple variables named i,j, and k in different scopes.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Sunshine, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to Speed Up My Program
    By purestr999 in forum C++ Programming
    Replies: 8
    Last Post: 03-23-2011, 08:23 AM
  2. Issue with program that's calling a function and has a loop
    By tigerfansince84 in forum C++ Programming
    Replies: 9
    Last Post: 11-12-2008, 01:38 PM
  3. Gaussian Elimination
    By Fiverz in forum C Programming
    Replies: 1
    Last Post: 02-05-2003, 12:59 PM
  4. Gaussian Elimination Problem
    By Inexorable in forum C Programming
    Replies: 1
    Last Post: 11-08-2002, 02:25 AM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 11:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21