- #1
Thereso
- 1
- 0
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:
program lolz
implicit none
real, external :: f
real y,c,x
! g(x,y) = x^2 + y
!calculate g(3.0,2.0)
y=2.0
open(26,file='y.dat',status='unknown')
write(26,*) (y)
close(26)
!test
x=3.0
write(*,*)"f(x) is",f(x)
end
function f (x)
implicit none
real f
real x,y
open(26,file='y.dat',status='unknown')
read(26,*) y
close(26)
f= x**2.0 +y
return
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
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:
program lolz
implicit none
real, external :: f
real y,c,x
! g(x,y) = x^2 + y
!calculate g(3.0,2.0)
y=2.0
open(26,file='y.dat',status='unknown')
write(26,*) (y)
close(26)
!test
x=3.0
write(*,*)"f(x) is",f(x)
end
function f (x)
implicit none
real f
real x,y
open(26,file='y.dat',status='unknown')
read(26,*) y
close(26)
f= x**2.0 +y
return
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