generate a sequence array in fortran

可紊 提交于 2021-02-07 05:34:15

问题


Is there an intrinsic in Fortran that generates an array containing a sequence of numbers from a to b, similar to python's range()

>>> range(1,5)
[1, 2, 3, 4]
>>> range(6,10)
[6, 7, 8, 9]

?


回答1:


No, there isn't.

You can, however, initialize an array with a constructor that does the same thing,


program arraycons
  implicit none
  integer :: i
  real :: a(10) = (/(i, i=2,20, 2)/)
  print *, a
end program arraycons




回答2:


If you need to support floats, here is a Fortran subroutine similar to linspace in NumPy and MATLAB.


! Generates evenly spaced numbers from `from` to `to` (inclusive).
!
! Inputs:
! -------
!
! from, to : the lower and upper boundaries of the numbers to generate
!
! Outputs:
! -------
!
! array : Array of evenly spaced numbers
!
subroutine linspace(from, to, array)
    real(dp), intent(in) :: from, to
    real(dp), intent(out) :: array(:)
    real(dp) :: range
    integer :: n, i
    n = size(array)
    range = to - from

    if (n == 0) return

    if (n == 1) then
        array(1) = from
        return
    end if


    do i=1, n
        array(i) = from + range * (i - 1) / (n - 1)
    end do
end subroutine

Usage:

real(dp) :: array(5)
call linspace(from=0._dp, to=1._dp, array=array)

Outputs the array

[0., 0.25, 0.5, 0.75, 1.]

Here dp is

integer, parameter :: dp = selected_real_kind(p = 15, r = 307) ! Double precision



回答3:


It is possible to create a function that reproduces precisely the functionality of range in python:

module mod_python_utils
contains
  pure function range(n1,n2,dn_)
     integer,           intent(in) :: n1,n2
     integer, optional, intent(in) :: dn_
     integer, allocatable :: range(:)
     integer ::dn
     dn=1; if(present(dn_))dn=dn_
     if(dn<=0)then
        allocate(range(0))
     else
        allocate(range(1+(n2-n1)/dn))
        range=[(i,i=n1,n2,dn)]
     endif
  end function range
end module mod_python_utils

program testRange
   use mod_python_utils
   implicit none
   integer, allocatable :: v(:)
   v=range(51,70)
   print"(*(i0,x))",v
   v=range(-3,30,2)
   print"(*(i0,x))",v
   print"(*(i0,x))",range(1,100,3)
   print"(*(i0,x))",range(1,100,-3)
end program testRange

The output of the above is

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
-3 -1 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29
1 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64 67 70 73 76 79 82 85 88 91 94 97 100

Notice that :

  1. the last line is empty: Fortran treats graciously zero-length arrays.
  2. allocated variables get automatically deallocated once out of scope.


来源:https://stackoverflow.com/questions/4691824/generate-a-sequence-array-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!