tsogam
tsogam

Reputation: 51

Complex variable function

I want to create a function FUN(x) which takes x as an argument which is complex variable, but I didn't make it. I searched but hadn't found any useful information. Can anybody help me?

    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

Upvotes: 0

Views: 1186

Answers (2)

wander95
wander95

Reputation: 1366

First of all, avoid implicit typing. Here is what I got working. Details will be added later:

  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

One should also use the KIND parameter. I will upgrade this later with better practices and a longer explanation. But for now, the above edit should explain you your mistake. High Performance Mark just updated the answer the more explanation.

Upvotes: 0

High Performance Mark
High Performance Mark

Reputation: 78354

Since implicit typing is not the answer, here's something a little closer to good 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

Upvotes: 3

Related Questions