在另一个函数中调用一个函数(在子例程中定义)

时间:2014-11-29 13:01:31

标签: fortran

我在fortran中为函数func(x,y)编写2D积分代码,y从y1(x)到y2(x)的限制和x从x1 = 3到x2 = 5的限制。 基本假设如下: 积分[func(x,y),{y = y1至y2},{x = x1至x2}] =积分[funcx(x),{x = x1至x2}]。其中funcx = Integral [func,{y = y1(x)to y2(x)}]

请在代码中间找到我的问题。我按如下方式编写代码,

implicit real*8(a-h,o-z)

external func
external y1
external y2

x1 = 3.d0
x2 = 5.d0

call twodint(func,y1,y2,x1,x2,result)
print*, result

stop
end

!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~

subroutine twodint(origfunc,y1,y2,x1,x2,result) 
implicit real*8(a-h,o-z)
external funcx
call simpsonintegral(funcx,x1,x2,ss) ! my integral routine funcx = function, x1 and x2 = limits, ss = output 
result = ss
return
end

!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~

function funcx(x)
implicit real*8(a-h,o-z)
external funcy
external y1
external y2
common/xvalues/xx
xx = x
call simpsonintegral(funcy,y1(x),y2(x),ss)
funcx = ss
return
end

!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~

function funcy(y)
implicit real*8(a-h,o-z)
common/xvalues/x

!我的问题:如果我在这里写funcy = func(x,y),我的代码工作正常。但是我想在这里写一些类似funcy = origfunc(x,y)的内容,以便它可以从名为twodint的子程序接收函数。但这不起作用。请帮忙...     返回     端

!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~

function func(x,y)
implicit real*8(a-h,o-z)
func = (x**2)*y*dsin(x*y) ! some function of x and y
return
end

function y1(x)
implicit real*8(a-h,o-z)
y1 = x ! some limit
return
end

function y2(x)
implicit real*8(a-h,o-z)
y2 = x*x ! some limit
return
end

1 个答案:

答案 0 :(得分:0)

在我看来,由于遗留原因,external主要包含在现代Fortran中。它不是将函数传递给子例程的最佳方法。此外,隐式类型声明是危险的...更好地使用implicit none并明确键入所有变量......你会以这种方式捕获很多错误。所以...这里是如何将各种函数传递给子程序(如积分器)的草图。

module MyStuff

implicit none

abstract interface
  function funcX (x)
      real, intent (in) :: x
      real :: funcX
  end function funcX
end interface



contains

subroutine twodint(origfunc,y1,y2,x1,x2,result)

real :: y1, y2, x1, x2, result, ss
procedure (funcX) :: origfunc

call simpsonintegral (origfunc,x1,x2,ss) ! my integral routine funcx = function, x1 and x2 = limits, ss = output
result = ss
return
end subroutine twodint


real function funcA (x)
real, intent (in) :: x
funcA = x ** 2
end function funcA

real function funcB (x)
real, intent (in) :: x
funcB = x ** 2
end function funcB

end module MyStuff


program test1

use MyStuff

implicit none



real :: x1, x2, y1, y2, result


x1 = 3.d0
x2 = 5.d0

call twodint(funcA,y1,y2,x1,x2,result)
print*, result

call twodint(funcB,y1,y2,x1,x2,result)
print*, result

stop
end program test1