2

我在使用 fortran 计算 e^x 内部和区间 [ba] 的积分时遇到了一些麻烦。

我想我在函数调用中做错了什么。谢谢你帮助我。

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
4

1 回答 1

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 

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

于 2013-10-31T21:12:28.710 回答