I have an issue in my program. The intrinsic function sum called with a mask leads to suspicious results: when I perform an average, I obtain a value out of the array bounds. I suspect this is related to rounding errors. I am working with large arrays and the rounding errors lead to large deviations (difference around 40% compared with the expected value for a size of 40,000 elements).
Below is a minimal example to reproduce it, and the associated output.
program main
implicit none
integer :: nelem
real, allocatable, dimension(:) :: real_array
logical, allocatable, dimension(:) :: log_array
! init
nelem=40000
allocate(real_array(nelem))
allocate(log_array(nelem))
real_array=0.
log_array=.true.
! Fill arrays
real_array=1./2000.
log_array = real_array.le.(0.5)
! Test
print *, ' test : ', &
count(log_array)+sum(real_array, mask=log_array), &
sum(1.+real_array,mask=log_array)
end program main
Ouput is :
test : 40019.9961 40011.9961
Theoretical results is 40020.
Running GNU Fortran (GCC) 4.9.0