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

Fortran Fortran 90/95 function

  1. Dec 17, 2015 #1
    Hello everyone! I've been wondering if it is possible in Fortran to 'read' a function.For instance when I code this:
    Code (Fortran):
    function f(x)
       double precision :: f
       double precision ::x
       f=(whatever the function)
    end function
    end program
    It would be ideal if the program allowed the user to type the function each time, rather than having it pre-set by the programmer.Thanks in advance!
  2. jcsd
  3. Dec 17, 2015 #2


    User Avatar
    Science Advisor
    Homework Helper
    2017 Award

    Fortran is a compiled language. If you need this interpreting feature, you'll have to build a parser or something.
    You can have function names as subroutine parameters (look up 'external'), but those functions have to be known and available at link time.
  4. Dec 17, 2015 #3


    Staff: Mentor

    To expand on what BvU said, you don't "input" a function. What comes into your program is essentially text, so if the user types "sqrt", your program needs to parse this string to get its semantic meaning; i.e., that you want to call the sqrt() function. Although the string "sqrt" and the function name sqrt appear the same to us, they are very different as far as the program is concerned.
  5. Dec 18, 2015 #4
    You have two options here.
    1. You could use a parser/interpreter. Either write one yourself or use an existing one, e.g. http://fparser.sourceforge.net
    2. If you need more performance you can also compile the function at runtime. That could for example be done by having your program send code through the Fortran compiler and then execute it. Of course languages with a built in just in time compiler like JavaScript would make this kind of thing a lot easier. JavaScript offers an "eval" function that can compile any code you give it at runtime making it execute a lot faster than any interpreter could.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook