Function to solve a system using Gauss-Seidel - c

I'm trying to write a function in order to solve a system of equations using the Gauss-Seidel method. The function I have so far doesn't do the job. The code stops giving me output after "Enter an initial guess..." and doesn't solve the function I'm inputting. Is this an issue with my function or some other part of my code?
/* code to solve a nxn system using the Gauss-Seidel method */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define MAX_DIM 100
#define MAX_ITER 500
#define TOLERANCE 1.e-6
void gauss_seidel(double a[][MAX_DIM], double b[], double x[], int n);
void main()
{
int i, j, n;
int violation_counter, answer;
int violation_rows[MAX_DIM];
double sum;
double a[MAX_DIM][MAX_DIM];
double b[MAX_DIM], x[MAX_DIM];
/* read in data */
n = MAX_DIM + 1;
while (n > MAX_DIM) {
printf("Enter the dimension of the system to be solved: ");
scanf_s("%d", &n);
}
printf("\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("Enter a[%d][%d] element of the system matrix: ",i,j);
scanf_s("%lf", &a[i][j]);
}
printf("Enter b[%d] of the right-hand-side vector: ", i);
scanf_s("%lf", &b[i]);
printf("\n");
}
/* test the convergence criterion */
violation_counter = 0;
for (i = 0; i < n; i++) {
sum = 0.0;
for (j = 0; j < n; j++)
if (i != j)
sum = sum + fabs(a[i][j]);
if (fabs(a[i][i]) < sum) {
violation_rows[violation_counter] = i;
violation_counter = violation_counter + 1;
}
if (a[i][i] == 0.0) {
printf("Found diagonal element equal to zero; rearrange equations; exiting ...\n");
exit(0);
}
}
if (violation_counter > 0) {
printf("The Gauss-Seidel convergence criterion is violated in %d rows out of %d\n", violation_counter, n);
printf("Specifically, it was violated in rows:\n");
for (i = 0; i < violation_counter; i++)
printf("%d ", violation_rows[i]);
printf("\n");
printf("Enter 1 if you want to continue; any other number to abort : ");
scanf_s("%d", &answer);
if (answer != 1)
exit(1);
printf("Check results carefully\n\n");
}
/* initialize the solution vector -- initial guesses */
for (i = 0; i < n; i++) {
printf("Enter an initial guess for x[%d] of the solution vector : ",i);
scanf_s("%lf", &x[i]);
}
/* solve the system */
gauss_seidel(a, b, x, n);
/* output solution */
for (i = 0; i < n; i++)
printf("x[%d]=%f\n", i, x[i]);
printf("\n");
}
/* function to solve a system using Gauss-Seidel */
void gauss_seidel(double a[][MAX_DIM], double b[], double x[], int n)
{
double maxerror = 1.0;
double iteration_error;
double e, sum, temp;
int i, j;
while (maxerror > 1.e-6) {
iteration_error = 0.0;
for (i = 0; i < n; i++) {
sum = 0.0;
for (j = 0; j < n; j++) {
if (i != j)
sum = sum + (a[i][j] * x[j]);
}
}
temp = (a[i][n] - sum) / a[i][i];
e = fabs((temp - x[i]) / x[i]);
x[i] = temp;
if (e > iteration_error)
iteration_error = e;
}
maxerror = iteration_error;
}

Related

How to raise a matrix to a power with double pointers in C

I am trying to raise a matrix to a power, using pointers but there is a mistake in my code I can't find.
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
>
int **alloc(int r, int c) {
int **d;
d = (int **)malloc(r * sizeof(int *));
for (int i = 0; i < r; i++) {
d[i] = (int *)malloc(c * sizeof(int));
}
return d;
void input(int **A, int r, int c) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("[%d][%d]=", i, j);
scanf_s("%d", &A[i][j]);
}
}
}
void output(int **A, int r, int c) {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("%d ", A[i][j]);
}
printf("\n");
}
}
void power(int **A,int**D, int r, int c,int p) {
int i, j,k;
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
D[i][j] = A[i][j];
}
}
while (p) {
// this is the matrix multiplication, where I attempt to multiply my matrix A with itself, and store the result in D, which initially started as A's copy, and p is the power I'm raising it to.
for (i = 0; i < r; i++) {
for (j = 0; j < c; j++) {
for (k = 0; k < c; k++)
D[i][j] = D[i][j] + A[i][k] * D[k][j];
}
}
p--;
}
}
void main() {
int r, c;
int **A, **D;
printf("rows A: ");
scanf_s("%d", &r);
printf("columns A: ");
scanf_s("%d", &c);
A = alloc(r, c);
printf("\nValues of A:\n");
input(A, r, c);
printf("\nMatrIX A is:\n");
output(A, r, c);
D = alloc(r, c);
printf("input the value you want to raise your matrix to: ");
int p;
scanf_s("%d", &p);
power(A, D, r, c, p);
printf("\nMatrix raised to said power is:\n");
output(D, r, c);
_getch();
}
When I input the rows and columns as 2 each, and input all values in the matrix as 1 and raise it to the power of 3, my answer should be
4 4
4 4
instead of
72 72
232 232
What is wrong in my code? If I were to print the D matrix before the multiplication, it would print it correctly, as:
1 1
1 1
Your two-step allocation looks okay, except that you don't free the memory after you're done. Your problem is in how you multiply the matrix:
Raising a matrix to a power involves multiplying it to itself. You can only do that if the matrix is square. You can replace all occurrences of rows r and columns c with a single dimension n.
When you do the actual multiplication:
D[i][j] = D[i][j] + A[i][k] * D[k][j];
you assign to D and read from it at the same time. Subsequent calculations (of the same multiplication) will see a changed value of D[i][j]. You will need a temporary "scratch" matrix.
Your code multiplies once too many. Also, Raising a matrix to the power of zero should yield the identity matrix.
Here's how your power function could look like:
void power(int **A, int **D, int n, int p)
{
int i, j,k;
// assign identity matrix to result D
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
D[i][j] = (i == j);
}
}
// create a scratch matrix
int **tmp = alloc(n);
while (p-- > 0) {
// multiply [tmp] = [A] * [D]
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
tmp[i][j] = 0;
for (k = 0; k < n; k++)
tmp[i][j] += A[i][k] * D[k][j];
}
}
// copy [D] = [tmp]
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
D[i][j] = tmp[i][j];
}
}
}
// TODO: clean up the scratch matrix
}

c program stops executing without any errors

in function calcdist() program stops running sometimes.
is it my computer or my code?
The program takes size for a 2d array (a square parking slot) then take the cars, after that finds best slot for our car.
best slot must have the largest distance to the nearest point.
distance is calculating by using manhatten distance.
most of the printf s for finding where the problem is.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define CAPACITY 50
int calcdist(int x, int y, int carnum[][CAPACITY], int size);
int main ()
{
int size, numofcars, x, y, mindist = 0, bestx = 0, besty = 0;
printf("Size: ");
scanf("%d", &size);
int carnum[size][size];
printf("Cars: ");
scanf("%d", &numofcars);
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
carnum[i][j] = 0;
}
}
for(int i = 0; i < numofcars; i++){
printf("Locations: ");
scanf("%d %d", &x, &y);
carnum[x - 1][y - 1] = 1;
}
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
printf("%d ",carnum[i][j]);
}
printf("\n");
}
printf("carnum[3][0]: %d\n",carnum[3][0]);
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
if(carnum[i][j] == 0){
printf("hi ");
if(mindist < calcdist(i, j, carnum, size)){
mindist = calcdist(i, j, carnum, size);
bestx = i + 1;
besty = j + 1;
printf("mindist is %d\n", calcdist(i, j, carnum, size));
}
}
}
}
printf("Best Slot Found In: %d %d\n", bestx, besty);
return 0;
}
int calcdist(int x, int y, int carnum[][CAPACITY], int size){
int dist = size * 2;
printf("x is: %d y is : %d\n", x, y);
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++){
printf("i is: %d j is : %d ", i, j);
if((carnum[i][j] == 1) && (dist > (abs(x - i) + abs(y - j) ))){
dist = abs(x - i) + abs(y - j);
}
printf("i is: %d j is : %d\n", i, j);
}
}
return dist;
}
/****** && (logical and) not & (unary operator) ******/
if((carnum[i][j] == 1) && (dist > (abs(x - i) + abs(y - j) )))

C - Two dimensional matrix, add in a shape of two symmetrical up-down triangles (almost like X)

The objective: Add only the pieces of the matrix that are part of a full X (upper and lower triangle).
1 1 1
0 1 0
1 1 1
Like this, middle one should add only once.
I can't add the lower triangle properly. Help much appreciated :)
void write(int niz[20][20], int n){
int i, j;
for(i=0; i<n; i++){
for(j=0; j<n; j++){
scanf("%d", &niz[i][j]);
}
}
}
void x(int niz[20][20], int n){
//Upper triangle
int i, j, pr=n, suma=0;
for(i=0; i<n/2 + n%2; i++,pr--){
for(j=i; j<pr; j++){
suma += niz[i][j];
}
}
printf("%d\n",suma);
//Lower triangle
pr = n;
for(i=n; i>n/2 + n%2; i--,pr--){
printf("%d",pr);
for(j=n-i; j<pr; j++){
printf("\n%d", niz[i][j]);
suma += niz[i][j];
}
}
printf("%d", suma);
}
int main()
{
int n;
printf("Matrix dimensions: ");
scanf("%d", &n);
printf("Numbers in the matrix: \n");
int niz[n][n];
write(niz, n);
x(niz, n);
}
Instead of writing separate functions for each lower, upper & diagonals you can do all together with little tricks, but it works only if row == column and thats's what you want I think.
int main() {
/* it can be anything like a[3][3] or a[7][7] and elements can
be all one or all 2 or any number */
int arr[5][5] = { {1,1,1,1,1},
{0,0,1,0,0},
{0,0,1,0,0},
{0,0,1,0,0},
{1,1,1,1,1} };
int row = sizeof(arr)/sizeof(arr[0]);
int col = sizeof(arr[0])/sizeof(arr[0][0]);
int sum = 0;
for(int index = 0; index < row; index++) {
for(int sub_index = 0; sub_index < col; sub_index++) {
if(index == 0 || (index == row-1) || sub_index == row/2)
sum = sum + arr[index][sub_index];
}
}
printf("sum = %d \n",sum);
return 0;
}
Its fine if it helps you otherwise write your own logic.
There are some mismatches between the declarations and types of the arguments passed to OP's function. While in main they declare a variable length array, named niz:
int n;
// ...
int niz[n][n];
The posted signature of both write and x requires an int niz(*)[20]. It should be changed to:
void write(int n, int niz[n][n]);
// this ^^^ may be a size_t, just remember to write it before the array
About the pattern you have to follow for the sum, I can't say to fully understand your requirement, but if I'm not completely wrong, it could be done this way:
#include <stdio.h>
#include <stdlib.h>
void read_matrix(int n, int niz[n][n])
{
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
scanf("%d", &niz[i][j]);
}
}
}
// Separate the calculation from the printing
int hourglass_sum(int n, int niz[n][n])
{
int sum = 0;
int i = 0;
//Upper triangle
for(int k = n; i < k; ++i, --k) {
for(int j = i; j < k; ++j) {
sum += niz[i][j];
}
}
//Lower triangle
for(int k = i + 1; i < n; ++i, ++k) {
for(int j = n - i - 1; j < k; ++j) {
sum += niz[i][j];
}
}
return sum;
}
int main()
{
int n;
printf("Matrix dimensions: ");
scanf("%d", &n);
int niz[n][n];
read_matrix(n, niz);
printf("\nSum: %d", hourglass_sum(n, niz));
}

Row with the biggest sum in matrix

I have a program where I enter numbers to make a matrix. Then it sums numbers in each row and prints the sum. But I need to print even the row with the biggest sum. Can someone please help me? Thanks. http://onlinemovies.pw
Here is the code:
#include <stdio.h>
int main (void)
{
static int array [10][10];
int i, j, m, n, sum = 0;
printf ("Enter the order of the matrix\n");
scanf ("%d %d", &m, &n);
printf ("Enter the co-efficients of the matrix \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf ("%d", &array [i][j]);
}
}
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
sum = sum + array[i][j] ;
}
printf ("Sum of the %d row is = %d\n", i, sum);
sum = 0;
}
}
You need to declare a variable and intialize it with a minimum value, if those values are always positive you can initialize it to 0:
int max = 0;
if not, you can use INT_MIN defined in <limits.h>
#include <limits.h>
...
int max = INT_MIN;
then use it in your loop:
int max = INT_MIN, imax = 0;
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
sum = sum + array[i][j] ;
}
printf ("Sum of the %d row is = %d\n", i, sum);
if (sum > max) {
max = sum;
imax = i;
}
sum = 0;
}
printf ("Max row (%d) is = %d\n", imax, max);

Code doesn't read input file correctly

My code doesn't seem to be able to read the input file correctly. It somehow only reads the first line of my matrix and then it inputs the second line under "right hand side" instead of making another line for the matrix under "coefficient matrix". Additionally, it prints the third line under "Initial Guesses" rather than the third line of the matrix.
I'm assuming the error is somewhere in the code that I have posted below but let me know if you believe the code below is correct and somewhere else in my code is where this problem is originating from.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define MAX_DIM 100
#define MAX_ITER 500
#define TOLERANCE 1.e-6
void gauss_seidel(double **a, double *b, double *x, int n);
void print_screen_A_b_x(double **a, double *b, double *x, int n);
void main()
{
int i, j, *ptr, n;
int violation_counter, answer;
int violation_rows[MAX_DIM];
double sum;
double **a;
double *b, *x;
FILE *input_Ptr; //pointer to input file
//Open the input file
input_Ptr = fopen ( "my_input.txt", "r" );
if (input_Ptr == NULL) {
puts("\nInput file was not opened succesfully.\n");
exit(-1);
}
//read size of the problem
fscanf(input_Ptr, "%d", &n);
//dynamic memory allocation
a = (double **) malloc (n * sizeof(double *));
for (i = 0; i < n; i++) {
a[i] = (double *) malloc (n * sizeof(double));
}
b = (double *) malloc (n * sizeof(double));
x = (double *) malloc (n * sizeof(double));
/* read in data */
//n = MAX_DIM + 1;
//while (n > MAX_DIM) {
//fscanf(input_Ptr, "%d", &n);
//}
printf("\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
fscanf(input_Ptr, "%lf", &a[i][j]);
}
for (i = 0; i < n; i++) {
fscanf(input_Ptr, "%lf", &b[i]);
}
for (i = 0; i < n; i++) {
fscanf(input_Ptr, "%lf", &x[i]);
}
printf("\n");
}
fclose(input_Ptr);
print_screen_A_b_x(a, b, x, n);
puts("Solution vector:");
for (i = 0; i < n; i++) {
printf("x[%d] = %10.5f \n", i, x[i]);
//free memory
for (i = 0; i < n; i++) {
free(a[i]);
}
free(a);
free(b);
free(x);
return 0;
}
/* test the convergence criterion */
violation_counter = 0;
for (i = 0; i < n; i++) {
sum = 0.0;
for (j = 0; j < n; j++)
if (i != j)
sum = sum + fabs(a[i][j]);
if (fabs(a[i][i]) < sum) {
violation_rows[violation_counter] = i;
violation_counter = violation_counter + 1;
}
if (a[i][i] == 0.0) {
printf("Found diagonal element equal to zero;
rearrange equations; exiting ...\n");
exit(0);
}
}
if (violation_counter > 0) {
printf("The Gauss-Seidel convergence criterion is violated in %d rows out of %d\n", violation_counter, n);
printf("Specifically, it was violated in rows:\n");
for (i = 0; i < violation_counter; i++)
printf("%d ", violation_rows[i]);
printf("\n");
printf("Enter 1 if you want to continue; any other number to abort : ");
scanf("%d", &answer);
if (answer != 1)
exit(1);
printf("Check results carefully\n\n");
}
/* initialize the solution vector -- initial guesses */
for (i = 0; i < n; i++) {
printf("Enter an initial guess for x[%d] of the solution vector : ", i);
scanf("%lf", &x[i]);
}
/* solve the system */
gauss_seidel(a, b, x, n);
/* output solution */
for (i = 0; i < n; i++)
printf("x[%d]=%f\n", i, x[i]);
printf("\n");
}
/* function to solve a system using Gauss-Seidel */
void gauss_seidel(double **a, double *b, double *x, int n)
{
double maxerror = 1.0e-7;
double iteration_error;
double e, sum, temp;
int i, j;
while (maxerror > 1.e-6) {
iteration_error = 0.0;
for (i = 0; i < n; i++) {
sum = 0.0;
for (j = 0; j < n; j++) {
if (i != j)
sum = sum + (a[i][j] * x[j]);
}
}
temp = (a[i][n] - sum) / a[i][i];
e = fabs((temp - x[i]) / x[i]);
x[i] = temp;
if (e > iteration_error)
iteration_error = e;
}
maxerror = iteration_error;
}
void print_screen_A_b_x(double **a, double *b, double *x, int n)
{
int i, j;
printf("\n Coefficient matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%10.2f", a[i][j]);
}
printf("\n");
}
printf("\n Right hand side vector:\n");
for (i = 0; i < n; i++) {
printf("%10.2f \n", b[i]);
}
printf("\n Initial guess:\n");
for (i = 0; i < n; i++) {
printf("%10.5f \n", x[i]);
}
return;
}
Add \r\n in your post loop if statement.
You show us:
void gauss_seidel(double a[][MAX_DIM], double b[], double x[], int n)
and:
void print_screen_A_b_x(double **a, double *b, double *x, int n)
You cannot pass the same object as the first argument to both functions; they are (radically) different types, even though you use double subscripts with both. Since you've not shown how the matrix is actually defined, there isn't anything more we can do to help you.
Your compiler should be shrieking at you about one (or both) calls. Heed your compiler. It knows more about C than you do at the moment. It won't object unless there's a serious problem. If by some mischance your compiler was not complaining, then you need to either turn on compilation warnings (and work with C11, or perhaps C99, as the version of the standard — definitely not C90) or get a better compiler.
Analysis of one update
One version of the updated code in the question has input code like this:
// read size of the problem
fscanf(input_Ptr, "%d", &n);
// dynamic memory allocation
a = (double **)malloc(n * sizeof(double *));
for (i = 0; i < n; i++)
{
a[i] = (double *)malloc(n * sizeof(double));
}
b = (double *)malloc(n * sizeof(double));
x = (double *)malloc(n * sizeof(double));
printf("\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
fscanf(input_Ptr, "%lf", &a[i][j]);
}
for (i = 0; i < n; i++)
{
fscanf(input_Ptr, "%lf", &b[i]);
}
for (i = 0; i < n; i++)
{
fscanf(input_Ptr, "%lf", &x[i]);
}
printf("\n");
}
The good news is that except for the absence of error checking, the memory allocation looks OK.
The bad news is that under most plausible inferences of what the data looks like, the main input loops are completely wrong. Assuming the value in n is N, the first iteration of the input loop reads N values into a[0] (which is fine), and then reads N values into b (which is fine as far as it goes), and then reads N values into x (which is also fine as far as it goes). The value of i is now n; when it is incremented by the outer loop, i is bigger than n, so the outer loop terminates, but you've only read one row of the main matrix.
Most likely, you should be using:
// read size of the problem
if (fscanf(input_Ptr, "%d", &n) != 1)
…report error and skedaddle…
// Check n for plausibility
if (n < 1 || n > 1000)
…report implausibility and skedaddle…
// dynamic memory allocation
…as before, except you should error check all the allocations…
printf("\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (fscanf(input_Ptr, "%lf", &a[i][j]) != 1)
…report error and skedaddle…
}
}
for (i = 0; i < n; i++)
{
if (fscanf(input_Ptr, "%lf", &b[i]) != 1)
…report error and skedaddle…
}
for (i = 0; i < n; i++)
{
if (fscanf(input_Ptr, "%lf", &x[i]) != 1)
…report error and skedaddle…
}
The fact that you don't check for errors means you don't know when things go wrong. You can't afford not to know when things go wrong, so you can't afford not to check for errors.
skedaddle |skɪˈdad(ə)l|
verb [ no obj. ] informal —
depart quickly or hurriedly; run away.

Resources