求一个fortran解决线性方程的代码.
来源:学生作业帮 编辑:搜搜考试网作业帮 分类:综合作业 时间:2024/08/18 20:47:01
求一个fortran解决线性方程的代码.
补充:用高斯消元法,要求有例子的.
补充:用高斯消元法,要求有例子的.
![求一个fortran解决线性方程的代码.](/uploads/image/z/18529977-57-7.jpg?t=%E6%B1%82%E4%B8%80%E4%B8%AAfortran%E8%A7%A3%E5%86%B3%E7%BA%BF%E6%80%A7%E6%96%B9%E7%A8%8B%E7%9A%84%E4%BB%A3%E7%A0%81.)
我运行通过了~~
program main
implicit none
integer :: N = 3
real*8 :: A(3,3) = (/ 2, 3, 1, 1, 1, 2, 1, 2, 2 /)
real*8 :: B(3) = (/ 4, 6, 5/), X(3)
call LinearGauss (A, B, X, N)
write(*,*) X
end
!-------------------------------------------------
! 行尺度高斯消元法
!-------------------------------------------------
subroutine LinearGauss (A, B, X, N)
implicit none
integer :: N
real*8 :: A(N, N), B(N), X(N)
real*8 :: z
integer,allocatable :: p(:), s(:)
integer :: i, j, k, sl
allocate (p(N))
allocate (s(N))
do i=1, N
p(i) = i
s(i) = MaxVal ( Abs(A(i, :)) )
end do
do k=1, N-1
j = k
do i=k+1, N
if ( Abs(A(p(j), k)) / s(p(j)) < Abs(A(p(i), k)) / s(p(i)) ) then
j = i
end if
end do
sl = p(k)
p(k) = p(j)
p(j) = sl
do i=k+1, N
z = A(p(i), k) / A(p(k), k)
A(p(i), k) = z
do j=k+1, N
A(p(i), j) = A(p(i), j) - z * A(p(k), j)
end do
end do
end do
do k=1, N-1
do i=k+1, N
B(p(i)) = B(p(i)) - A(p(i), k) * b(p(k))
end do
end do
do i=N, 1, -1
z = 0
do j=i+1, N
z = z + A(p(i), j) * X(j)
end do
X(i) = (B(p(i)) - z) / A(p(i), i)
end do
end subroutine
program main
implicit none
integer :: N = 3
real*8 :: A(3,3) = (/ 2, 3, 1, 1, 1, 2, 1, 2, 2 /)
real*8 :: B(3) = (/ 4, 6, 5/), X(3)
call LinearGauss (A, B, X, N)
write(*,*) X
end
!-------------------------------------------------
! 行尺度高斯消元法
!-------------------------------------------------
subroutine LinearGauss (A, B, X, N)
implicit none
integer :: N
real*8 :: A(N, N), B(N), X(N)
real*8 :: z
integer,allocatable :: p(:), s(:)
integer :: i, j, k, sl
allocate (p(N))
allocate (s(N))
do i=1, N
p(i) = i
s(i) = MaxVal ( Abs(A(i, :)) )
end do
do k=1, N-1
j = k
do i=k+1, N
if ( Abs(A(p(j), k)) / s(p(j)) < Abs(A(p(i), k)) / s(p(i)) ) then
j = i
end if
end do
sl = p(k)
p(k) = p(j)
p(j) = sl
do i=k+1, N
z = A(p(i), k) / A(p(k), k)
A(p(i), k) = z
do j=k+1, N
A(p(i), j) = A(p(i), j) - z * A(p(k), j)
end do
end do
end do
do k=1, N-1
do i=k+1, N
B(p(i)) = B(p(i)) - A(p(i), k) * b(p(k))
end do
end do
do i=N, 1, -1
z = 0
do j=i+1, N
z = z + A(p(i), j) * X(j)
end do
X(i) = (B(p(i)) - z) / A(p(i), i)
end do
end subroutine