Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- class Jacobi{
- private:
- float a[10][10], b[10], x[10];
- int n;
- public:
- Jacobi(float x[10][10], float b1[10], int m);
- void jacobi();
- void display();
- };
- Jacobi::Jacobi(float x[10][10], float b1[10], int m){
- int i, j;
- n = m;
- for(i = 0; i < n; i++){
- for(j = 0; j < n; j++)
- a[i][j] = x[i][j];
- b[i] = b1[i];
- }
- }
- void Jacobi::jacobi(){
- float s;
- float xg[10], e[10], eps;
- int i, j, k, itr, flag;
- flag = 0;
- itr = 0; // itr = number of iterations
- eps = 1e-6; // eps = lowest value of difference of two consecutive roots
- // To initialize guess values
- for(i = 0; i < n; i++){
- xg[i] = 0;
- }
- // Jacobi iteration starts
- while(flag == 0){
- // Assuming convergence is reached
- flag = 1;
- itr = itr + 1;
- for(i = 0; i < n; i++){
- s = 0;
- for(j = 0; j < n; j++)
- if(i != j){
- // For Jacobi
- s = s + a[i][j] * xg[j];
- }
- x[i] = (b[i] - s) / a[i][i];
- e[i] = x[i] - xg[i];
- if(e[i] < 0)
- e[i] = -e[i];
- }
- // To check value of e[]
- for(i = 0; i < n; i++)
- if(e[i] > eps){
- flag = 0;
- break;
- }
- // To change guess values
- for(i = 0; i < n; i++){
- xg[i] = x[i];
- }
- }
- cout << "\nTotal number of Iterations taken = " << itr << endl;
- display();
- }
- void Jacobi::display(){
- int i;
- cout << "Solutions of Linear Simultaneous Equations: \n";
- for(i = 0; i < n; i++){
- cout << "x[" << i + 1 << "] = " << x[i] << endl;
- }
- }
- int main(void) {
- system("cls");
- float a[10][10], b[10];
- int i, j, n;
- cout << "Enter the number of simultaneous equations(1-10): ";
- cin >> n;
- cout << "Enter the coefficients of all equations\n";
- for(i = 0; i < n; i++){
- for(j = 0; j < n; j++){
- cout << "a[" << i << "][" << j << "] = ";
- cin >> a[i][j];
- }
- cout << "b[" << i << "] = ";
- cin >> b[i];
- }
- Jacobi J(a, b, n);
- J.jacobi();
- return 0;
- }
Add Comment
Please, Sign In to add comment