1

I actually want to solve an n variable hamilton's sets of equations. In fortran,to define a function, we, generally do the following.

function H(x,p) result(s)
real::x,p,s
s=x**2+p**2
end function H

Now, if I wish to solve an n variable hamilton's equation, I need to define an n variable H(x(i),p(i)) where i runs from 1 to n. Suppose p(i) are the variables and H is p(i)^2, summed over i from 1 to n.

What are the possible ways of defining a function with an array as input? It is not possible to write H(x1,x2....x100...) manuaaly each time.

5
  • Very quick, just write real, dimension(:) :: x,p,s Commented Jan 19, 2020 at 9:21
  • Can you please give an explicit example? Commented Jan 19, 2020 at 9:26
  • In fortran,to define a function, we, generally do the following. .... s=x^2+p^2 not with those funny little hat symbols we don't. Commented Jan 19, 2020 at 10:45
  • 1
    @kvantour perhaps elemental would be a better option ? But it's difficult to tell. Commented Jan 19, 2020 at 10:46
  • @HighPerformanceMark If H(x,p) really is that simple, elemental was also my immediate thought. It takes a while to wrap your head around array functions, side effects, etc. Commented Jan 23, 2020 at 3:59

1 Answer 1

2
module aa
  implicit none

  public :: H

contains
  function H(x,p) result(s)
    real, dimension(:), intent(in) :: x,p
    real, dimension(:), allocatable :: s
    integer :: i, n

    n = size(x, 1)
    allocate(s(n))

    do i=1, n
       s(i) = x(i)**2 + p(i)**2
    enddo
  end function H
end module aa

program test
  use aa

  real, dimension(10) :: x, p
  real, dimension(:), allocatable :: s
  integer :: n

  x(:) = 1.
  p(:) = 1.

  n = size(x, 1)
  allocate(s(n))
  s(:) = 0.

  s = H(x,p)

  print*, s
end program test

Compiled and tested with GNU Fortran (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0

This is not really a real case program example because if you know the dimensions of x and p, you also know the dimensions of s, so you could have just defined it instead of allocating. But it can be used to generalize modules once there is no reference to any dimension in the module.

For this to work, you will notice that s must be allocatable and must have been allocated before calling the function.

Sign up to request clarification or add additional context in comments.

3 Comments

Did you test this? See comment from High Performance Mark with the question.
Fixed. I haven't compiled, was writing by heart because I've done this specific kind of function a lot, but I mixed the math part with other languages. Thanks!
Changed for a version which can be compiled out of the box.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.