【问题标题】:Problems with the Trapezoidal Rule梯形规则的问题
【发布时间】:2013-10-31 21:02:02
【问题描述】:

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

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

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

【问题讨论】:

  • 我不确定您的代码中的数学运算是否正确...为什么即使用户可以指定完全不同的限制,您也总是从f(1) 开始并转到f(n-1)?你不应该以(a-b)/n 的步骤从a 转到b 吗?为什么在这里使用整数?
  • i = 1 到 n-1 只计算出现在图像上的总和。计算 deltax 的限制 a 和 b。 [链接]imgur.com/uQOEGcS [/链接]

标签: fortran numerical calculus


【解决方案1】:

您的代码有几个问题:

  • 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 

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

【讨论】:

  • 现在我的程序可以编译了。我想我在声明方面犯了一些可怕的错误。现在算法编译了,但正如你所见,我需要修正数学。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 2018-06-29
  • 2016-07-12
  • 2014-12-17
  • 1970-01-01
相关资源
最近更新 更多