fortran format specifier for complex number

343_458 picture 343_458 · May 17, 2015 · Viewed 9.5k times · Source

Can I specify a format specifier for a complex number in fortran? I have a simple program.

program complx1
implicit none
complex :: var1
var1 = (10,20)
write (*,*) var1
write (*,'(F0.0)') var1
write (*,'(F0.0,A,F0.0)') real(var1), ' + i ' , aimag(var1)
end program complx1

Output:

 (  10.0000000    ,  20.0000000    )
10.
20.
10. + i 20.

I wanted to use inbuilt format for a+bi with some format specifier, instead of one did manually (second last line of program). Obviously F0.0 did not work. Any ideas?

EDIT: I don't think this is a duplicate of post: writing complex matrix in fortran, which says to use REAL and AIMAG functions. I already used those functions and wondering whether there is an inbuilt format that can do the work.

Answer

High Performance Mark picture High Performance Mark · May 18, 2015

An addendum to @francescalus' existing, and mostly satisfactory, answer. A format string such as

fmt = '(F0.0,SP,F0.0,"i")'

should result in a complex number being displayed with the correct sign between real and imaginary parts; no need to fiddle around with strings to get a plus sign in there.