Silverfrost Forums

Welcome to our forums

Array assignment using SPREAD, and an ELEMENTAL function requiring temporary arrays

29 Jan 2026 12:27 (Edited: 29 Jan 2026 12:32) #32756

The following code exposes a bug, the assignment z = peaks(spread(x,2,n), spread(y,1,n)) fails with FTN95 (access violation).

program p
use iso_fortran_env
implicit none
integer, parameter :: n = 4
integer :: i, j
real*8 :: x(n), y(n), z(n,n), zt1(n,n), zt2(n,n)
  write(*, '(a)') compiler_version()
  print*
  x = [0,1,2,3]
  y = [-3,-2,-1,0]
  write(*,'(a,1x,4(F10.5,2X))') 'X = ', x
  write(*,'(a,1x,4(F10.5,2X))') 'Y = ', y
  print*
  
  z = peaks(spread(x,dim=2,ncopies=n), spread(y,dim=1,ncopies=n))  ! ### FTN95 fails here

  write(*, '(a)')'z = peaks(spread(x,2,n), spread(y,1,n))'
  do j = 1, n
    write(*,'(4(F10.5,2X))') (z(i,j),i=1,n)
  end do
  print*

contains

  elemental function peaks (x,y) result (val)
  real*8, intent(in) :: x, y
  real*8 :: val
     val = 3.d0*(1.d0 - x)**2 * exp( -x**2 - (y+1.d0)**2 ) &
       - 10.d0*(x/5.d0 - x**3 - y**5) * exp( -x**2 - y**2 ) &
               - 1.d0/3.d0 * exp( -(x+1.d0)**2 - y**2 )
  end function peaks

end program p

The compiler actually has to do a lot of work “under the bonnet” to get to the final result, and this AI generated line of code defeats FTN95!

I can think of at least two different ways to achieve the required end result in a much clearer way.

Nevertheless z = peaks(spread(x,2,n), spread(y,1,n)) is all Fortran 90 syntax, so looks like a bug to me.

Here is the program’s output from an alternative compiler.

GCC version 12.3.0

X =     0.00000     1.00000     2.00000     3.00000
Y =    -3.00000    -2.00000    -1.00000     0.00000

z = peaks(spread(x,2,n), spread(y,1,n))
  -0.24495    -0.10996    -0.00431    -0.00001
  -4.75961    -2.10235    -0.06164     0.00042
  -0.72391    -0.27292     0.49964     0.01301
   0.98101     2.93693     1.41216     0.03312
29 Jan 2026 1:41 (Edited: 29 Jan 2026 1:43) #32757

Ken

Thank you for the feedback.

FTN95 does not currently support the use of SPREAD as an approach to parallelisation. The outcome is that runtimes can be excessively long or sometimes it fails to compile.

This approach was recommended in the Fortran 95 book by Metcalf, Reid and Cohen, and Numerical Recipes in Fortran 90, but it is only useful when parallelisation is supported.

For FTN95, AI generated code that uses SPREAD in this way should be converted back to its simpler Fortran 77 form.

29 Jan 2026 2:29 #32760

Thank you Paul, that's a very clear recommendation to be saved in to the AI's local user history.

Please login to reply.