Sei sulla pagina 1di 5

Problem 1: Write a menu driven program in C / C++ code for the above

algorithm. Menu should be of your own choice. Use this algorithm as a function
and solve m simultaneous equations with n unknowns. Find the conditions for
unique and no solution. If solution exists, find whether it is degenerate or not.
Try to draw the graph for it.

Problem 2:

(a) 3x - y = 8, x + y = 8 (Sol: (1, 2))


(b) 6x - 10y = 5, 2x - 3y = 1 (Sol: (7/2, -2))
(c) 2x - 8y = 9, x - 4y = -6 ( Sol: No solution)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double *X, *OX;

void jacobi(double **A, double *b, double tol, int n, int m){
int i,j;
double sum, norm;
for(i=0;i<m;i++){
sum=0;
for(j=0;j<n;j++){
if(j!=i){
sum=sum+A[i][j]*OX[j];
}
}
X[i] = (b[i]-sum)/A[i][i];
}
norm=0;
for(i=0;i<n;i++){
norm=norm+(OX[i]-X[i])*(OX[i]-X[i]);
}
if(sqrt(norm)<tol){
printf("[");
for(i=0;i<n;i++){
printf("%lf, ", X[i]);
}
printf("]\n");
exit(-1);
}
for(i=0;i<n;i++){
OX[i]=X[i];
}

int main()
{
int i, j, n, m, max_itr;
double **A, *b, tol;
printf("No. of variables:\n");
scanf("%d", &n);
printf("No. of equations:\n");
scanf("%d", &m);

A = (double **)malloc(m * sizeof(double));


for(i=0;i<m;i++){
A[i] = (double *)malloc(n * sizeof(double));
}

b = (double *)malloc(m * sizeof(double));

OX = (double *)malloc(n * sizeof(double));


X = (double *)malloc(n * sizeof(double));
printf("Give A matrix:\n");
for(i=0;i<m;i++){
for(j=0;j<n;j++){
scanf("%lf", &A[i][j]);
}
}

printf("Give b vector:\n");
for(i=0;i<m;i++){
scanf("%lf", &b[i]);
}

printf("Initial X:\n");
for(i=0;i<n;i++){
scanf("%lf", &OX[i]);
}

printf("Give tolerence:\n");
scanf("%lf", &tol);

printf("Give max. no. of iteration:\n");


scanf("%d", &max_itr);

for(i=0;i<max_itr;i++){
jacobi(A,b,tol,n,m);
}

printf("[");
for(i=0;i<n;i++){
printf("%lf, ", X[i]);
}
printf("]\n");

return 0;
}
No. of variables:
2
No. of equations:
2
Give A matrix:
3 -1
1. 1
Give b vector:
8
8
Initial X:
0
0
Give tolerence:
0.001
Give max. no. of iteration:
20

Output:
[4.000203, 4.000203, ]

No. of variables:
2
No. of equations:
2
Give A matrix:
2. -3
6 -10
Give b vector:
1
5
Initial X:
0
0
Give tolerence:
0.001
Give max. no. of iteration:
20

Output:
[-1.628304, -1.302643, ]

Potrebbero piacerti anche