1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <iostream> //libraries
#include <cmath>
using namespace std;
const int EPSILON = 1e-8; //global const to be used for approximations
int main ()
{
const int SIZE = 4; //size of the arrrays
double x[SIZE] = {}; //1D x array
double A[SIZE][SIZE] = { //2D A array
{9, -4, -2, 0},
{-4, 17, -6, -3},
{-2, -6, 14, -6},
{0, -3, -6, 11}
};
double b[SIZE] = {24, -16, 0, 18};
double newx[4];
bool converge = false; //setting the initial convergence to false
cout << "Please enter an initial guess to the solution" << endl;
cin >> x[0] >> x[1] >> x[2] >> x[3]; //the guess
while ( converge == false )
{
newx[0] =(1/A[0][0])*(b[0] - ((A[0][1]*x[1]) + (A[0][2]*x[2]) + (A[0][3]*x[3])));
newx[1] =(1/A[1][1])*(b[1] - ((A[1][0]*x[0]) + (A[1][2]*x[2]) + (A[1][3]*x[3])));
newx[2] =(1/A[2][2])*(b[2] - ((A[2][0]*x[0]) + (A[2][1]*x[1]) + (A[2][3]*x[3])));
newx[3] =(1/A[3][3])*(b[3] - ((A[3][0]*x[0]) + (A[3][1]*x[1]) + (A[3][2]*x[2])));
converge = abs(newx[0] - x[0]) < EPSILON //checking convergence
&& abs(newx[1] - x[1]) < EPSILON
&& abs(newx[2] - x[2]) < EPSILON
&& abs(newx[3] - x[3]) < EPSILON;
x[0] = newx[0];
x[1] = newx[1];
x[2] = newx[2];
x[3] = newx[3];
cout << x[0] << "," << x[1] << "," << x[2] << "," << x[3] << endl;
}
}
|