Question

I have a section of code that's producing different results under gfortran between a debug build and an optimized build.

PROGRAM test

IMPLICIT NONE

REAL, DIMENSION(10) :: a = 0.0
REAL, DIMENSION(10) :: b = 1.0

WRITE (*,*) b
WHERE (a .ne. 0.0) b = a
WRITE (*,*) b

END PROGRAM

When I compile this as a debug build, it produces the correct result. When I compile it as an optimized build, it replacing every element of b with a.

$ gfortran test.f
$ ./a.out
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
$ gfortran -O3 test.f
$ ./a.out
1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0     
0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 

If this is a compiler bug, how can I work around it?

Was it helpful?

Solution

I cannot reproduce your problem. I'm using

gcc version 4.9.0 20140313 (experimental) (GCC)

on x86_64-unknown-linux-gnu (Ubuntu 12.04 amd64). For me, your example program results in:

$ gfortran where.f $ ./a.out 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000
1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000
$ gfortran -O3 where.f $ ./a.out 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000
1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000 1.00000000

So, which version of gfortran are you using? Remember that 4.9 is not yet released, so the date of your prerelease version may be significant. Furthermore, which target (that is, OS & bitness) are you using? If you built GCC yourself, did you run the GCC testsuite to check that your gfortran build works otherwise and is not hopelessly broken?

OTHER TIPS

There's nothing wrong with your code and the Intel Fortran compiler produces the same, correct, output with and without the -O3 flag. While, as @eriktous points out, there are delicacies to be observed when comparing floating-point numbers, both 0 and 1 are precisely representable (certainly on any machine which implements IEEE floating-point arithmetic) and comparisons for equality such as your code exhibits should be fine.

If this is a compiler bug, and I suspect that it might be, the usual workaround would be to use another compiler (version).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top