我期待傳遞一個語句函數在另一個函數中進行評估,這可能嗎?我想要一個可以在數值上集成一般函數的函數。在我真正的問題中還有其他值,所以我不想有一個外部函數。Fortran傳遞語句函數到函數
編輯2014年11月1日02:22 GMT
有一對情侶在代碼@IanH投入的錯誤。這是我照顧的錯誤後,其運作的代碼。
program trapezoidZ
implicit none
! main program global variables and constants here.
call main
contains
subroutine main
real :: u, integral1
integer :: i
integer, parameter :: n = 5000
! delete declaration of trapezoid_integration and f.
integral1 = trapezoid_integration(TrigSin, n, 0., 3.14159/2.0)
write (*,*) "I - Trap = ",1 - integral1
end subroutine main
function my_f(u)
real :: my_f
real, intent(in) :: u
my_f = (u**4)*EXP(u)/((EXP(u)-1.0)**2)
end function my_f
function TrigSin(u) result(my_f)
real :: my_f
real, intent(in) :: u
my_f = sin(u)
end function TrigSin
function trapezoid_integration (f, n, start_val, end_val) result (integral)
! delete declaration of integrand (assuming you have it).
procedure(my_f) :: f
integer :: n
real :: start_val, end_val
real :: integral,u,h
integer :: i
integral = 0.0
do i=0,n
u = start_val + ((end_val - start_val)*i)/n
! implement Eqn G.4
if ((i.eq.0).or.(i.eq.n)) then
integral = integral+integrand(f, u)
else
integral = integral+(2.0*integrand(f, u))
end if
end do
h=(end_val - start_val)/n
integral = (h/2.0)*integral
end function trapezoid_integration
function integrand(f, x) result (value)
implicit none
real :: x
real :: value
real :: f
if (x .lt. 0.00001) then
x = 0.00001
end if
value = f(x)
end function integrand
end program trapezoidZ
下面這個是原代碼。不要使用
program trapezoidZ
implicit none
integer, parameter :: n = 10
real :: u, integral
integer :: i
real :: f, trapezoid_integration
f(u) = (u**4)*EXP(u)/((EXP(u)-1.0)**2)
integral = trapezoid_integration(f, n, 0.2, 3.0)
write (*,*) '#trapezoidal integration = ',integral
end program trapezoidZ
function trapezoid_integration(f, n, start_val, end_val)
implicit none
integer :: n
real :: start_val, end_val
real :: f
real :: integral,u,h
integer :: i
integral = 0.0
do i=0,n
u = start_val + ((end_val - start_val)*i)/n
! implement Eqn G.4
if ((i.eq.0).or.(i.eq.n)) then
integral = integral+integrand(f, u)
else
integral = integral+(2.0*integrand(f, u))
end if
end do
h=(end_val - start_val)/n
integral = (h/2.0)*integral
end subroutine trapezoid_integration
function integrand(f, x) result (value)
implicit none
real :: x
real :: value
real :: f
if (x .lt. 0.00001) then
x = 0.00001
end if
value = f(x)
end function integrand
此代碼中有輕微的錯誤。我把最後的運行版本放在原文中。 – user1543042 2014-11-01 02:29:32