|Apr15-12, 04:22 PM||#1|
Fortran passing parameters to a function of one variable
Hi all! I have a question about fortran. So far in my coding, if i wanted to define a function ( say f(x) ) I would manually set a grid for x, and then define f for each x value, so that i would have a vector for f and a vector for x. However, I'd now like to use the 'function' command, so i can call f for ANY x.
I'll do my best to explain my question: say I define a function g(x,y) by
g(x,y) = x**2 + y
and I want to define another function f(x), which is EQUAL to g(x,y) but with y held constant. I want to use a set of subroutines on the function f, but the problem is that all of the subroutines call f as a function of one variable and not two. So basically I want to pass y as a parameter into a function defining f(x). Later I will change y and then repeat. One way I can do it is to write y to a data file, and then read it from inside the function f:
real, external :: f
! g(x,y) = x^2 + y
function f (x)
f= x**2.0 +y
end function f
this program correctly returns "f(x) is 11.". But I'm sure that this constant opening and closing of data files is inefficient, there must be a better way of doing it? Thanks everyone :D
|Apr15-12, 05:56 PM||#2|
Well...I don't quite get what you REALLY are trying to achieve...why can't you just pass x AND y to the function f? ...just declare the function f to take two parameters and return one...nothing wrong with that.
Other than that, you could use common block (up to fortran 77 style) to set y before you start calling the function with just x; or, you could go the module/use route (fortran 90 forward style). These two methods allow the function and the main program to share values without having to pass them around as arguments/parameters.
|Apr15-12, 08:23 PM||#3|
The way to do this in fortran 77 is use a common block, something like
function f(x) common/fcom/y ... g(x,y) ... end program main common/fcom/y ... y = 2.0 ... f(x) ... y = 3.0 ... f(x) ... end
|Similar Threads for: Fortran passing parameters to a function of one variable|
|Passing parameters||Programming & Comp Sci||2|
|Passing variables between subroutines in different files using Fortran||Programming & Comp Sci||3|
|Fortran: Passing loop names to subroutines||Programming & Comp Sci||5|
|Fortran: Passing integers to type dimension||Programming & Comp Sci||2|
|Fortran 90/95 : passing parameters to functions||Programming & Comp Sci||4|