2

I need to calculate a complex function for different x values, something like

(i+1) exp(i * x) / x

I see that my option is to expand it in terms of sin and cos, and then separate out real and imaginary parts manually by hand, to be able to calculate them individually in code, and then define my complex function. This is a relatively simple function, but I have some bigger ones, not so easy to segregate manually into two components.

Am I missing something or this is the only way?

EDIT : I am pasting the sample code which works after helpful comments from everyone below, hope it's useful :

program complex_func
  IMPLICIT  NONE
  
Real(8) x
complex CF

x = 0.7
call complex_example(x, CF)
write(*,*) CF

end program complex_func


Subroutine complex_example(y, my_CF)

  Implicit None
  Real(8) y
  Complex my_CF
  complex, parameter :: i = (0, 1)  ! sqrt(-1)
  my_CF = (i+1) * exp(i*y) / y
  
  !my_CF = cmplx(1, 1) * exp(cmplx(0.0, y)) / y !!THIS WORKS, TOO
  write(*,*) my_CF
  
  return
  
end Subroutine complex_example
ZeroTwo
  • 307
  • 1
  • 3
  • 12
  • 1
    The FORTRAN EXP function supports complex arguments !?! –  May 25 '21 at 11:40
  • 2
    Try something like `cmplx(1, y=1) * exp(cmplx(0.0, y=x)) / x`. Many intrinsics are overloaded for complex arguments. – jack May 25 '21 at 11:41
  • 2
    Not even necessary to use cmplx for `(i+1)`, it is just `(1, 1)`. – Vladimir F Героям слава May 25 '21 at 11:42
  • 1
    @YvesDaoust Note it is officially spelt Fortran, lower case. And yes, complex is a first class type in Fortran so the (vast majority of) the intrinsic types support it. – Ian Bush May 25 '21 at 12:01
  • @IanBush: I was referring to the versions I practiced most, namely FORTRAN IV and FORTRAN 77. :-) –  May 25 '21 at 12:04
  • Thanks, everyone! And thanks @jack, what you suggested worked perfectly! – ZeroTwo May 25 '21 at 12:11
  • 1
    This works, too! `complex, parameter :: i = (0, 1)` `(i+1) * exp(i*x) / x` – ZeroTwo May 25 '21 at 12:19
  • 1
    You shouldn't be using hard-coded kind values no more, e.g. `real(8)`. See this [question](https://stackoverflow.com/q/838310/10774817) for more info. – jack May 25 '21 at 12:41

0 Answers0