|
如果高斯消去程序本身没有问题,则需要看看系数矩阵的条件数。过高的条件数可以导致高斯法不能运算或给出错误解(误差过大)。对于条件数比较的系数矩阵,可以采用双精度数据格式,情况会好一点。
最简单的高斯消去法程序如下。此程序经过检验没有错误,如果不能计算说明方程本身有问题。这个程序只适用于小规模并且系数矩阵规范的情况,不是很实用。推荐使用Lapack 3 或者 slatec 中的程序模块。这些模块都附带用来检验有效位数的子程序。Lapack 3 或者 slatec 都是免费的,在网上可以找到。
!==============================================================================
function sl(a,b)
! linear solver using gaussian elimination for full matrix
! solve a*x=b, a: n-by-n matrix, b: n-by-1 array
! note: this function is only efficient on small matrix!
! ------------------------------------------------------------------------------
implicit none
! ------------------------------------------------------------------------------
! declare dummy variables
double precision, dimension(:,:), intent(in) :: a
double precision, dimension(:), intent(in) :: b
double precision, dimension(size(b,1)):: sl
! ------------------------------------------------------------------------------
! declare local variables
integer:: i,j,k,n
double precision:: sum,xx
double precision, dimension(size(a,1),size(a,2)):: aa
double precision, dimension(size(b,1)):: bb
! ------------------------------------------------------------------------------
sl=0.0d0
n=size(b,1)
aa=a
bb=b
! convert to upper triangular form
do k = 1,n-1
if (dabs(aa(k,k)).gt.1.d-6) then
do i = k+1, n
xx = aa(i,k)/aa(k,k)
do j = k+1, n
aa(i,j) = aa(i,j) - aa(k,j)*xx
end do
bb(i) = bb(i) - bb(k)*xx
end do
else
write (*,'("zero pivot found in line ",i5)') k
stop
end if
end do
! ------------------------------------------------------------------------------
! back substitution
do i = n,1,-1
sum = bb(i)
if (i.lt.n) then
do j= i+1,n
sum = sum - aa(i,j)*bb(j)
end do
end if
bb(i) = sum/aa(i,i)
end do
sl=bb
! ------------------------------------------------------------------------------
end function sl
! ------------------------------------------------------------------------------
! note: to use the function, add the following interface to the caller
! interface
! function sl(a,b)
! double precision, dimension(:,:), intent(in) :: a
! double precision, dimension(:), intent(in) :: b
! double precision, dimension(size(b,1)):: sl
! end function sl
! end interface
! ============================================================================== |
评分
-
1
查看全部评分
-
|