为了获得正确的结果,我需要更改Simpson的Rule Fortran代码吗?

时间:2019-02-19 09:43:11

标签: fortran simpsons-rule

我正在尝试实现一段代码,以通过使用Simpson's Rule获得积分来获得曲线下的面积。

!(file:/// D:/1-%20TUD/Semester%201/Numerical%20Methods%20BIWO-04/Lectures/simpson's%20rule.JPG)

我已经使用MatchCAD尝试过,并且得到了正确的结果 函数:f(x)= x**5+(x-2)*sin(x)+(x-1)

program simpsons

  implicit none

  real a, b, h
  real integ, fa, fb
  integer i, m

  write(*,*) 'enter the lower boundary'
  read(*,*) a
  write(*,*) 'enter the upper boundary'
  read(*,*) b

  do while(a.ge.b)
    write(*,*) 'reenter the lower boundary'
    read(*,*) a
    write(*,*) 'reenter the upper boundary'
    read(*,*) b
  enddo

  write(*,*) 'enter the intervals number'
  read(*,*) m

  h=(b-a)/2.0

  fa=a**5.0+(a-2.0)*sin(a)+(a-1.0)
  fb=b**5.0+(b-2.0)*sin(b)+(b-1.0)

  integ=0

  do i=1, m/2

    integ=integ+4*((a+(2*i-1)*h)**5.0+((a+(2*i-1)*h)-2.0)*sin((a+(2*i-1)*h))+ ((a+(2*i-1)*h)-1.0))

    if (i.le.((m/2)-1)) then

      integ=integ+2*((a+2*i*h)**5.0+((a+2*i*h)-2.0)*sin((a+2*i*h))+((a+2*i*h)-1.0))

    endif
  enddo

  integ=(fa+fb+integ)*(h/3.0)

  write(*,*) 'integration = ', integ
end

当我输入a=-1b=1m=20时,我应该获得Integration = -1.398

当我输入a=-1b=1m=40时,我应该获得Integration = -1.398

但是以某种方式我正在获得集成= 7015869.0

1 个答案:

答案 0 :(得分:2)

我前一段时间正在使用此代码。如@VladimirF所指出的,最好将函数f(x)与算法simpson(f,a,b,integral,n)分开。

program main
  implicit none
  double precision a, b, integral
  integer n

  a = -1; b = 1; n = 20
  call simpson(f,a,b,integral,n)
  write (*,*) 'integration = ', integral

contains 

function f(x)
  implicit none
  double precision f, x
  f = x**5 + (x-2)*sin(x) + (x-1)
end

Subroutine simpson(f,a,b,integral,n)
  implicit none
  double precision f, a, b, integral, s
  double precision h, x
  integer n, i

  ! if n is odd we add +1 to make it even
  if((n/2)*2.ne.n) n = n+1

  ! loop over n (number of intervals)
  s = 0.0
  h = (b-a)/dble(n)
  do i = 2, n-2, 2
     x = a + i*h
     s = s + 2.0*f(x) + 4.0*f(x+h)
  end do
  integral = (s + f(a) + f(b) + 4.0*f(a+h))*h/3.0
end subroutine simpson

end program main

具有正确的输出: integration = -1.39766605364858