Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Fortran, why do i suddenly get new errors?

  1. May 9, 2012 #1
    Do subroutines return values only?

    Sorry for the wrong title!

    I currently have a subroutine which should return y like (the actual formula is a bit more complex): y=cos(t)

    When i call the subroutine and then make a do-loop to test y for different t, it gives 1 value only. Does the subroutine give a value to y or am I doing something else wrong?

    t doesn't have a value before the subroutine is called.
     
    Last edited: May 9, 2012
  2. jcsd
  3. May 9, 2012 #2

    Mark44

    Staff: Mentor

    Re: Do subroutines return values only?

    Fortran subroutines don't return values. By that, I mean that an expression that includes a subroutine call doesn't evaluate to anything.

    Your routine should be a FUNCTION, which does return a value.
     
  4. May 9, 2012 #3
    Re: Do subroutines return values only?

    I have something like this, it's not about wether or not a subroutine is needed, I want to understand how it works.

    Code (Text):
    call asd(y,t,a)
    do i=1,10
    t=i
    test(i)=y
    end do

    subroutine asd(y,t,a)
    y=a*cos(t)
    end
    For some reason test(i) gives the same value for every i, whereas the following works as i want it to, note that t doesn't have a value before the subroutine call.
    Code (Text):
    do i=1,10
    t=i
    test(i)=a*cos(t)
    end do
     
     
    Last edited: May 9, 2012
  5. May 9, 2012 #4

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    If your first code you only call the subroutine once. You need to call it inside the loop like this.
    Code (Text):

    do i=1,10
        t=i
        call asd(y,t,a)
        test(i)=y
    end do
     
    You don't really need the variable y. You could do
    Code (Text):

    do i=1,10
        t=i
        call asd(test(i),t,a)
    end do
     
    (Note, you DO need t, because by default t is a real variable and i is an integer, so
    call asd(y,i,a) won't work. (It will probably compile, but give you the wrong answers).
     
  6. May 9, 2012 #5
    Ok, thanks I think I get it now. As soon as y has a value it's no longer a*cos(t), so by taking the subroutine in the loop, y get's redeclared as a*cos(t) every single loop, after which y can be calculated with a new t again.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook