Fortran 90/95 function

  • #1
21
2
Hello everyone! I've been wondering if it is possible in Fortran to 'read' a function.For instance when I code this:
Fortran:
contains
function f(x)
   double precision :: f
   double precision ::x
   f=(whatever the function)
   return
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!
 

Answers and Replies

  • #2
BvU
Science Advisor
Homework Helper
13,881
3,432
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.
 
  • #3
34,534
6,230
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.
 
  • #4
521
70
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.
 

Related Threads on Fortran 90/95 function

Replies
4
Views
10K
Replies
5
Views
11K
  • Last Post
Replies
1
Views
6K
Replies
1
Views
8K
Replies
4
Views
37K
  • Last Post
Replies
2
Views
6K
Replies
3
Views
2K
Replies
5
Views
6K
Replies
2
Views
2K
Replies
2
Views
6K
Top