用Fortran语言编写subroutine程序,用高斯迭代法解线性方程组
时间: 2024-02-06 11:11:08 浏览: 119
高斯迭代法求线性方程组
4星 · 用户满意度95%
以下是使用高斯迭代法求解线性方程组的Fortran语言程序:
```fortran
PROGRAM gauss_seidel
IMPLICIT NONE
INTEGER, PARAMETER :: N = 3
INTEGER :: max_iter = 1000
REAL :: tol = 1e-6
REAL :: error = 0.0, sum = 0.0
REAL :: a(N,N) = RESHAPE([4.0, 1.0, -1.0, &
2.0, 7.0, 1.0, &
1.0, -3.0, 12.0], [N,N])
REAL :: b(N) = [3.0, -5.0, 14.0]
REAL :: x(N) = [0.0, 0.0, 0.0]
REAL :: x_new(N)
CALL gauss_seidel(a, b, x, max_iter, tol)
DO i = 1, N
WRITE(*,*) "x(", i, ") = ", x(i)
END DO
CONTAINS
SUBROUTINE gauss_seidel(a, b, x, max_iter, tol)
IMPLICIT NONE
INTEGER, INTENT(IN) :: max_iter
REAL, INTENT(IN) :: tol
REAL, INTENT(IN) :: a(N,N), b(N)
REAL, INTENT(INOUT) :: x(N)
REAL :: x_new(N)
INTEGER :: iter, i, j
iter = 0
DO WHILE (iter < max_iter)
DO i = 1, N
sum = 0.0
DO j = 1, N
IF (j /= i) THEN
sum = sum + a(i,j) * x(j)
END IF
END DO
x_new(i) = (b(i) - sum) / a(i,i)
END DO
error = ABS(x_new(1) - x(1))
DO i = 1, N
error = MAX(error, ABS(x_new(i) - x(i)))
x(i) = x_new(i)
END DO
IF (error < tol) THEN
WRITE(*,*) "Converged after ", iter+1, " iterations"
RETURN
END IF
iter = iter + 1
END DO
WRITE(*,*) "Failed to converge after ", max_iter, " iterations"
END SUBROUTINE gauss_seidel
END PROGRAM gauss_seidel
```
在程序中,首先定义了线性方程组的系数矩阵`a`、常数向量`b`和待求解的未知向量`x`,以及最大迭代次数`max_iter`和容差`tol`。然后调用了名为`gauss_seidel`的子程序,使用高斯迭代法求解线性方程组。在`gauss_seidel`子程序中,循环迭代直到达到最大迭代次数或者解收敛。每次迭代中,对于每个未知量,计算其新的值,然后计算当前解的误差,如果误差小于容差,则认为已经收敛,返回结果。如果迭代次数达到最大值,但仍未收敛,则返回失败。最后在`main`程序中,输出解的结果。
需要注意的是,在Fortran中,数组下标从1开始而不是从0开始。此外,由于Fortran的语法特点,需要在子程序开头添加`IMPLICIT NONE`语句来禁止隐式声明变量。
阅读全文