复变函数

Complex variable function

我想创建一个函数 FUN(x),它将 x 作为复杂变量的参数,但我没有成功。我搜索但没有找到任何有用的信息。有谁能够帮助我?

    program Console2

IMPLICIT REAL *8 (A-H,O-W) 
external FUN
complex:: b

b=(2,2)

print*,FUN(b)

end program Console2

  FUNCTION FUN (x)    
  IMPLICIT REAL *8 (A-H,O-W) 
  complex, intent(in) :: x 
  complex :: a
  a=(1,2)

  FUN=x+a
  RETURN 

END

由于隐式键入不是答案,这里有一些更接近好的 Fortran 的东西...

program console2

  use, intrinsic :: iso_fortran_env
  ! this module defines portable kind type parameters incl real64

  implicit none
  ! so no errors arising from forgotten declarations or misunderstood
  ! implicit declarations

  complex(kind=real64):: b
  ! for a complex number each part will have the same size as a real64
  ! no trying to figure out complex*8 or complex*16 

  b=(2,2)

  print*,fun(b)

contains
  ! by 'containing' the function definition we get the compiler to check
  ! its interface at compile time; properly called *host-association* and in
  ! a larger program we might use a module instead

  complex(kind=real64) function fun (x)    
    complex(kind=real64), intent(in) :: x
    complex(kind=real64) :: a

    a=(1,2)
    fun=x+a

  end function fun

end program console2

首先,避免隐式键入。这是我的工作。详情稍后补充:

  program Console2

  ! good programming practice
  IMPLICIT NONE
  external FUN
  complex:: b
  complex:: FUN                                                                                                                              

  b=(2,2)

  print*,FUN(b)
  end program Console2

  COMPLEX FUNCTION FUN (x)
  IMPLICIT NONE
   complex, intent(in) :: x
   complex :: a
   a=(1.0,2.0)   ! a=(1,2)

   FUN=x+a
   RETURN
   END

还应该使用 KIND 参数。我稍后会用更好的做法和更长的解释来升级它。但是现在,上面的编辑应该可以解释你的错误。高性能标记刚刚更新了更多解释的答案。