In Fortran, there is no built-in function called linspace like in some other programming languages.
However, you can easily create a similar functionality by writing a subroutine or a function that generates an array of equally spaced values.
Example
- In this example, the linspace subroutine takes four arguments: start, end, num, and result.
- It calculates the step size by dividing the range (end – start) by the number of values minus one (num – 1).
- Then, it fills the result array with equally spaced values using a loop.
subroutine linspace(start, end, num, result)
implicit none
real, intent(in) :: start, end
integer, intent(in) :: num
real, intent(out) :: result(num)
real :: step
integer :: i
step = (end - start) / (num - 1)
do i = 1, num
result(i) = start + (i - 1) * step
end do
end subroutine linspace
program linspace_example
implicit none
real :: start_val, end_val
integer :: num_vals, i
real, allocatable :: values(:)
start_val = 0.0
end_val = 1.0
num_vals = 10
allocate(values(num_vals))
call linspace(start_val, end_val, num_vals, values)
do i = 1, num_vals
print *, values(i)
end do
deallocate(values)
end program linspace_example
Output
0.00000000
0.111111104
0.222222209
0.333333313
0.444444418
0.555555582
0.666666687
0.777777791
0.888888896
1.00000000