追赶法_解线性方程组的直接解法

追赶法_解线性方程组的直接解法

标签:计算方法实验

#include 

const int maxn = 15;

int main()
{
    /*
    数据存储格式: a[]对角线上, b[]对角线, c[]对角线下, f[]右端常数
    double a[N] = {0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1};
    double b[N] = {0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4};
    double c[N] = {0, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0};
    double f[N] = {7, 5, -13, 2, 6, -12, 14, -4, 5, -5};
    double x[N] = {0}, u[N] = {0}, y[N] = {0};
    */
    freopen("zgf.txt", "r", stdin);
    freopen("ans.txt", "w", stdout);

    double a[maxn] = {0}, b[maxn] = {0}, c[maxn] = {0}, f[maxn] = {0}, x[maxn] = {0}, u[maxn] = {0}, y[maxn] = {0};
    int n, N;
    scanf("%d", &n);
    N = n + 1;  //0列不使用
    scanf("%lf %lf %lf", &b[1], &a[2], &f[1]);
    for(int i = 2; i < N - 1; i++)  scanf("%lf %lf %lf %lf", &c[i - 1], &b[i], &a[i + 1], &f[i]);
    scanf("%lf %lf %lf", &c[N - 1], &b[N - 1], &f[N - 1]);

    //追
    u[1] = c[1] / b[1];  //L1 == b[1]
    y[1] = f[1] / b[1];
    for(int i = 2; i < N - 1; i++)
    {
        double l = b[i] - a[i] * u[i - 1];  //克洛特分解A = LU
        u[i] = c[i] / l;

        y[i] = (f[i] - a[i] * y[i - 1]) / l;
    }
    y[N - 1] = (f[N - 1] - a[N - 1] * y[N - 2]) / (b[N - 1] - a[N - 1] * u[N - 2]);
    //赶
    x[N - 1] = y[N - 1];
    for(int i = N - 2; i >= 1; i--)  x[i] = y[i] - u[i] * x[i + 1];
    for(int i = 1; i < N; i++)  printf("x%d = %f\n", i, x[i]);

    return 0;
}

数据文件
追赶法_解线性方程组的直接解法_第1张图片
实验结果
追赶法_解线性方程组的直接解法_第2张图片

你可能感兴趣的:(计算方法实验)