定义一个函数返回一个数组 [英] Defining a function returning an array
问题描述
我有以下的code:
Program function_as_an_array
implicit none
integer:: i
integer, parameter:: N=10
real*8:: x(N),y(N),f(N)
do i=1,N
x(i)=float(i)
end do
call func(f,N,x)
open(unit=20, file='test.dat')
do i=1,N
y(i)=f(i)
write(20,*) x(i),y(i)
end do
close(20)
Stop
End Program function_as_an_array
Subroutine func(f,N,x)
implicit none
integer i,N
real*8:: x(N),f(N)
do i=1,N
f(i)=x(i)**2
end do
end Subroutine func
我想让程序的确可以意味着
函数作为arrray,即我想替换子程序FUNC
由函数f
并获得相同的结果(在主程序中,我想保留像 Y = F(X,N)声明
)。我该怎么做?
I want to make the program indeed be meant for
"function as an arrray", i.e. I would like to replace the Subroutine func
by a function f
and get the same result (In the main program, I wish to keep a statement like y=f(x,N)
). How can I do that?
感谢。
推荐答案
有有一个函数返回一个数组,与的这个问题,并回答:主要的问题是,你需要的功能是一个模块(或包含
ED内该计划),以便有一个自动显式接口:(修改添加:或明确定义的接口与亚历山大·沃格特的答案)
There's no problem having a function return an array, as with this question and answer: the main issue is that you need the function to be in a module (or contain
ed within the program) so that there's an automatic explicit interface: (Edit to add: or explicitly defining the interface as with Alexander Vogt's answer)
module functions
contains
function func(N,x)
implicit none
integer, intent(in) :: N
double precision, intent(in) :: x(N)
double precision, dimension(N) :: func
integer :: i
do i=1,N
func(i)=x(i)**2
end do
end function func
end module functions
Program function_as_an_array
use functions
implicit none
integer:: i
integer, parameter:: N=10
double precision:: x(N),y(N)
do i=1,N
x(i)=float(i)
end do
y = func(N,x)
open(unit=20, file='test.dat')
do i=1,N
write(20,*) x(i),y(i)
end do
close(20)
Stop
End Program function_as_an_array
但要注意,这样的功能 - 在阵列应用相同的操作,每一个元素 - 是较为精美,一个Fortran 进行元素
函数,定义工作只需标量和Fortran将自动映射过来给你一个数组的所有元素:
But note that this sort of function - applying the same operation to every element in array - is somewhat more nicely done with a Fortran elemental
function, defined to work simply on a scalar and Fortran will automatically map it over all elements of an array for you:
module functions
contains
elemental double precision function f(x)
implicit none
double precision, intent(in) :: x
f = x**2
end function f
end module functions
Program function_as_an_array
use functions
implicit none
integer:: i
integer, parameter:: N=10
double precision:: x(N),y(N)
do i=1,N
x(i)=float(i)
end do
y = f(x)
open(unit=20, file='test.dat')
do i=1,N
write(20,*) x(i),y(i)
end do
close(20)
Stop
End Program function_as_an_array
这个的好处是,它现在将标量工作,并自动任何级别的阵列。只要有可能,这是很好的让编译器做你的工作适合你。
The nice thing about this is that it will now work on scalars, and arrays of any rank automatically. Wherever possible, it's good to have the compiler do your work for you.
这篇关于定义一个函数返回一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!