线性方程组 Ax=b 求解(Chapter28)
来源:互联网 发布:cuda linux 编译 编辑:程序博客网 时间:2024/04/29 17:29
- *@LUDecomposition LU分解-详见上一篇或下一篇
- int LinearEquation(double **A, double *x, double *b, int size)
- {
- double **L, **U, *y;
- double temp;
- int i, j;
- L = (double**)malloc(sizeof(double*)*size);
- U = (double**)malloc(sizeof(double*)*size);
- for (i = 0; i < size; i++)
- {
- L[i] = (double*)malloc(sizeof(double)*size);
- U[i] = (double*)malloc(sizeof(double)*size);
- }
- if (!LUDecomposition(A, L, U, size))
- {
- fprintf(stderr, "Error: In LinearEquation./n");
- return 0;
- }
- y = (double*)malloc(sizeof(double)*size);
- for (i = 0; i < size; i++)
- {
- temp = 0;
- y[i] = 0;
- for (j = 0; j <= i-1; j++)
- temp += L[i][j] * y[j];
- y[i] += b[i] - temp;
- }
- for (i = size-1; i >= 0; i--)
- {
- temp = 0;
- x[i] = 0;
- for (j = i+1; j < size; j++)
- temp += U[i][j] * x[j];
- x[i] = (y[i] - temp) / U[i][i];
- }
- for (i = 0; i < size; i++)
- {
- free(L[i]);
- free(U[i]);
- }
- free(L);
- free(U);
- free(y);
- return 1;
- }