定义一个函数返回一个数组定义一个函数返回一个数组(Defining a function retur

2019-05-12 05:47发布

我有以下代码:

    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”,即我想更换Subroutine func一个function f ,并得到相同的结果(在主程序中,我想保留一份声明中像y=f(x,N) 我怎样才能做到这一点?

谢谢。

Answer 1:

还有有一个函数返回一个数组,如没有问题这个问题,回答 :主要的问题是,你需要的功能是一个模块(或contain在程序中编),以便有一个自动显式接口:( 编辑添加 :或明确定义的界面与亚历山大·沃格特的答案)

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语言做elemental功能,定义为一个标量只是工作和Fortran会自动在阵列中的所有元素映射为你:

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

关于这样做的好处是,它现在会自动标量,和任何级别的阵列上工作。 只要有可能,这是很好的让编译器做你的工作你。



Answer 2:

这是为我工作:

Program function_as_an_array
implicit none
integer:: i
integer, parameter:: N=10
real*8 :: x(N),y(N),f(N)
interface func
  function func(x,N) result(f)
    implicit none
    integer N
    real*8:: x(N),f(N) 
  end function
end interface

do i=1,N
  x(i)=float(i)
end do

f = func(x,N)

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


function func(x,N) result(f)
implicit none
integer i, N
real*8:: x(N),f(N) 

do i=1,N
   f(i)=x(i)**2
end do

end function

你需要:

  • 使用result为一个数组值返回变量[编辑],或指定FUNC作为real*8:: func(N) 详情请参阅意见。
  • 使用外部函数的显式接口(或具有隐式接口的模块,看到乔纳森·德西的答案)

然后,您可以直接分配功能的阵列的返回值。



文章来源: Defining a function returning an array