大家。
我正在使用中点规则和Simpson规则来计算[1,2]中x ^ 2的积分。我发现,在相同数量的子区间中,中点规则近似似乎比辛普森的规则近似更准确,这真的很奇怪。
中点规则近似的源代码是:
program midpoint
implicit none ! Turn off implicit typing
Integer, parameter :: n=100 ! Number of subintervals
integer :: i ! Loop index
real :: xlow=1.0, xhi=2.0 ! Bounds of integral
real :: dx ! Variable to hold width of subinterval
real :: sum ! Variable to hold sum
real :: xi ! Variable to hold location of ith subinterval
real :: fi ! Variable to value of function at ith subinterval
dx = (xhi-xlow)/(1.0*n) ! Calculate with of subinterval
sum = 0.0 ! Initialize sum
xi = xlow+0.5*dx ! Initialize value of xi
do i = 1,n,1 ! Initiate loop
! xi = xlow+(0.5+1.0*i)*dx
write(*,*) "i,xi ",i,xi ! Print intermidiate result
fi = xi**2 ! Evaluate function at ith point
sum = sum+fi*dx ! Accumulate sum
xi = xi+dx ! Increment location of ith point
end do ! Terminate loop
write(*,*) "sum =",sum
stop ! Stop execution of the program
end program midpoint
相应的执行是:
...... ..... ..................
i,xi 100 1.99499905
sum = 2.33332348
Simpson规则近似的源代码是:
program simpson
implicit none ! Turn off implicit typing
integer, parameter :: n=100 ! Number of subintervals
integer :: i=0 ! Loop index
real :: xlow=1.0, xhi=2.0 ! Bounds of integral
real :: h ! Variable to hold width of subinterval
real :: sum ! Variable to hold sum
real :: xi ! Variable to hold location of ith subinterval
real :: fi ! Variable to value of function at ith subinterval
real :: Psimp ! Variable of simpson polynomial of xi interval
h = (xhi-xlow)/(1.0*n) ! Calculate width of subinterval
sum = 0.0 ! Initialize sum
do while (xi<=xhi-h) ! Initiate loop
xi = xlow+i*2.0*h ! Increment of xi
i=i+1
write(*,*) "i,xi ",i,xi ! Print intermidiate result
Psimp=xi**2+4.0*(xi+h)**2+(xi+2.0*h)**2
! Evaluate function at ith point
sum = sum+(h/3.0)*Psimp ! Accumulate sum
end do ! Terminate loop
write(*,*) "sum =",sum
end program simpson
相应的执行是:
........ ...... ...................
i,xi 101 2.00000000
sum = 2.37353396
为了获得与中点结果相同的数字精度,我必须将Simpson程序中的子间隔数设置为100000,这比中点程序多1000倍(我最初将两个数字子区间设置为100)
我检查辛普森程序中的代码,但找不到什么错误。
如果我记得正确的话,辛普森的规则应该比中点规则更快地收敛。
Craig Burley曾经说过,一旦qzxswpoi循环看起来像循环的前提被违反,循环将立即退出。这里循环的前提是在WHILE
时被违反,但是循环在那个时刻没有中断,只有当完成整个迭代迭代并且测试可以应用在循环的顶部时。你可以更加一致地使用Fortran成语将循环转换为计算的x=xhi
循环
DO
然后评论出来
DO i = 0, n/2-1
线。或者只需在修改 i=i+1
后立即测试循环前提:
xi
对于Simpson规则,无论哪种方式都可以得到精度不高于3的多项式。