Hi all,
I ran into something strange with ASSOCIATE and the imaginary part selector %im.
here is a small example:
program hello
use, intrinsic :: iso_fortran_env, only: wp => real64, compiler_version
implicit none
real(wp) :: x = 0.0_wp
real(wp) :: h = 1.0e-50_wp
print *, "Compiler version:", compiler_version()
associate (r => f(cmplx(x, h, kind=wp)))
print *, "kind(r):", kind(r)
print *, "storage_size(r):", storage_size(r)
print *, "r = ", r
print *, 1.0_wp / h * r%im ! the correct result should be 1.0
print *, 1.0_wp / h * aimag(r) ! the correct result should be 1.0
end associate
contains
complex(wp) function f(x)
complex(wp), intent(in) :: x
f = sin(x)
end function f
end program hello
With gfortran 14.2.0 I get:
Compiler version:GCC version 14.2.0
kind(r): 4
storage_size(r): 64
r = (0.00000000,0.00000000)
0.0000000000000000
0.0000000000000000
I also tested with the latest version (online compiler https://godbolt.org/) and got the same output:
Compiler version:GCC version 17.0.0 20260502 (experimental)
kind(r): 4
storage_size(r): 64
r = (0.00000000,0.00000000)
0.0000000000000000 ! result should be 1.0
0.0000000000000000 ! result should be 1.0
However: if I comment out the line: print *, 1.0_wp / h * r%im the result printed by print *, 1.0_wp / h * aimag(r) becomes correct, i.e., returns 1.0
associate (r => f(cmplx(x, h, kind=wp)))
print *, "kind(r):", kind(r)
print *, "storage_size(r):", storage_size(r)
print *, "r = ", r
!print *, 1.0_wp / h * r%im ! <<<<<< if we comment out this
print *, 1.0_wp / h * aimag(r) ! <<< the result is now 1.0
end associate
Output:
Compiler version:GCC version 17.0.0 20260502 (experimental)
kind(r): 8
storage_size(r): 128
r = (0.0000000000000000,1.00000000000000001E-050)
1.0000000000000000
Is this a gfortran bug, or am I misunderstanding something about ASSOCIATE and complex part selectors?
Update:
With nagfor, the result is correct:
Compiler version:NAG Fortran Compiler Release 7.2(Shin-Urayasu) Build 7231
kind(r): 8
storage_size(r): 128
r = (0.0000000000000000,1.0000000000000000E-50)
1.0000000000000000
1.0000000000000000
End of update
Best,
Simo
