梯形法则存在的问题

时间:2013-10-31 21:02:03

标签: fortran numerical calculus

我在使用fortran来计算e ^ x inside和interval [b.a]的积分时遇到了一些麻烦。

我认为我在funcion调用中做错了。谢谢你的帮助。

program trapezium
  implicit none

    integer :: i, n, b, a
    real :: sumation, mean, deltax, f(i), integral


 ! The value of the integral using the trapezium rule can be found using
 ! integral = (b - a)*((f(a) +f(b))/2 + sumation_1_n-1 )/n 

write(*,*) "type the limits b, a and the number of intervals"
     read *, b, a, n

    deltax = (b - a)/n
        mean = (f(a) + f(b))/2
sumation = 0

do i = 1, n-1  
    sumation = sumation + f(i)
end do


      integral = deltax*(mean + sumation) 
  write (*,*) "the value of the integral using the trapezoidal method is", integral

     end program 

function f(x)
  real :: f(x) 
  integer :: x

      f(x) = EXP(x)

end function

1 个答案:

答案 0 :(得分:2)

您的代码存在一些问题:

  • f是一个函数,但同时您定义了一个数组f(i)
  • 定义固定大小的数组时,必须在编译时知道大小。因此real :: f(i)仅对常量i
  • 有效
  • exp()需要real变量,而不是整数
  • 整数算术可能会导致意外结果:1/2 = 0而非0.5

然而(这不会试图解决数学问题 - 请参阅我的评论):

module functions
contains
  function f(x)
    implicit none
    real :: f
    integer,intent(in) :: x

    f = EXP(real(x))

  end function
end module

program trapezium
  use functions
  implicit none

  integer :: i, n, b, a
  real :: sumation, mean, deltax, integral


  ! The value of the integral using the trapezium rule can be found using
  ! integral = (b - a)*((f(a) +f(b))/2 + sumation_1_n-1 )/n 

  write(*,*) "type the limits b, a and the number of intervals"
  read *, b, a, n

  deltax = real(b - a)/real(n)
  mean = (f(a) + f(b))/2
  sumation = 0

  do i = 1, n-1  
    sumation = sumation + f(i)
  end do


  integral = deltax*(mean + sumation) 
  write (*,*) "the value of the integral using the trapezoidal method is", integral

end program 

请注意,使用模块可以使编译器检查函数的参数。此外,您无需在主程序中定义函数的返回值。