实验1.5

吉林大学 计算方法实验课 实验1.5

代码用octave语言编写。

实验题目:

实验1.5_第1张图片

实验代码及现象:

(1)用实验1.2的矩阵

function x = jacobi1(n)
    %函数初始化
  A = zeros(n,n);
  b = zeros(n,1);
  x = zeros(n,1);
  for i=1:n
    A(i,i) = 3;
    if i < n
      A(i+1,i) = 9;
      A(i,i+1) = 1;
    end
    b(i) = 13;
  end
  b(1) = 4;
  b(n) = 12;
  %jacobi函数
  x0 = zeros(n,1);
  x = zeros(n,1);
  k=0;
  for i = 1:n
    x(i) = b(i);
    for j = 1:n-1
      x(i) = x(i)-A(i,j)*x0(j);
    end
    for j = i+1:n
      x(i) = x(i)-A(i,j)*x0(j);
    end
    x(i) = x(i)/A(i,i);
  end
  x
  while norm(x-x0) > exp(-10)
    k = k+1;
    x0 = x;
    for i = 1:n
      x(i) = b(i);
      for j = 1:i-1
        x(i) = x(i)-A(i,j)*x0(j);
      end
      for j = i+1:n
        x(i) = x(i)-A(i,j)*x0(j);
      end
      x(i) = x(i)/A(i,i);
    end
   x
  end
  endfunction

发现结果中x的指数越来越大,不收敛。

实验1.5_第2张图片实验1.5_第3张图片

(2)用实验1.5的矩阵

function x = jacobi1(n)
    %函数初始化
  A = zeros(n,n);
  b = zeros(n,1);
  x = zeros(n,1);
  for i=1:n
    A(i,i) = 13;
    if i < n
      A(i+1,i) = 9;
      A(i,i+1) = 1;
    end
    b(i) = 13;
  end
  b(1) = 4;
  b(n) = 12;
  %jacobi函数
  x0 = zeros(n,1);
  x = zeros(n,1);
  k=0;
  for i = 1:n
    x(i) = b(i);
    for j = 1:n-1
      x(i) = x(i)-A(i,j)*x0(j);
    end
    for j = i+1:n
      x(i) = x(i)-A(i,j)*x0(j);
    end
    x(i) = x(i)/A(i,i);
  end
  x
  while norm(x-x0) > exp(-10)
    k = k+1;
    x0 = x;
    for i = 1:n
      x(i) = b(i);
      for j = 1:i-1
        x(i) = x(i)-A(i,j)*x0(j);
      end
      for j = i+1:n
        x(i) = x(i)-A(i,j)*x0(j);
      end
      x(i) = x(i)/A(i,i);
    end
   x
  end
  endfunction

发现收敛。

最后收敛结果如下。

实验1.5_第4张图片



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