I'm sure the solution to this is extremely basic, but I'm having a hard time figuring out how to use functions in Fortran. I have the following simple program:
PROGRAM main
IMPLICIT NONE
INTEGER :: a,b
a = 3
b = 5
PRINT *,funct(a,b)
END PROGRAM
FUNCTION funct(a,b)
IMPLICIT NONE
INTEGER :: funct
INTEGER :: a,b
funct = a + b
END FUNCTION
I've tried several variations of this, including assigning a data type before FUNCTION, assigning the result of funct to another variable in the main program and printing that variable, and moving the FUNCTION block above the PROGRAM block. None of these worked. With the current program I get an error on line 6 (the line with the PRINT statement):
Error: Return type mismatch of function 'funct' (UNKNOWN/INTEGER(4))
Error: Function 'funct' has no IMPLICIT type
From all of the guides I've tried, I seem to be doing it right; at least one of the variations, or a combination of some of them, should have worked. How do I need to change this code to use the function?
Simply putting the function in the file will not make it accessible to the main program.
Traditionally, you could simply declare a function as external and the compiler would simply expect to find a suitable declaration at compile-time.
Modern Fortran organizes code and data in "modules". For your purpose, however, it is simpler to "contain" the function within the scope of the main program as follows:
PROGRAM main
IMPLICIT NONE
INTEGER :: a,b
a = 3
b = 5
PRINT *,funct(a,b)
CONTAINS
FUNCTION funct(a,b)
IMPLICIT NONE
INTEGER :: funct
INTEGER :: a,b
funct = a + b
END FUNCTION funct
END PROGRAM main
A simpler solution can be the following code
PROGRAM main
IMPLICIT NONE
INTEGER :: a,b, funct
a = 3
b = 5
PRINT *,funct(a,b)
END PROGRAM
FUNCTION funct(a,b)
IMPLICIT NONE
INTEGER :: funct
INTEGER :: a,b
funct = a + b
END FUNCTION
where the only difference is in the third line, where I have declared funct as an integer. It compiles and it prints 8 as result.
Related
I am writing a Fortran program to solve Euler Project problems. In my implementation each problem is a function, for example:
character(len=20) function euler_problem_0001()
use some_external_lib
...
end function euler_problem_0001
and if I print the function I simply get the answer.
print *, euler_problem_0001()
Now I have finished quite a few problems and I find it a bit tedious to write print *, euler_problem_xxxx() over and over again. So my questions is: Is there a way that I can construct a derived type that could link an integer (number of the problem) with the actual procedure? Something like
type, public :: int_to_proc
character(len=:) :: proc_name
procedure(proc_x), pointer :: proc_p
end type int_to_proc
so that if I initialize the type with an integer,
call int_to_proc%init(2)
then the type bound procedure pointer will point to the function euler_problem_0002(). In this case I only have to write a loop similar to this
type(int_to_proc) :: prob
do i = 1, 500
call prob%init(i)
print *, prob%proc_p()
end do
instead of writing 500 lines of print *, euler_problem_xxxx(). Also, any work-around is also welcome. Thanks!
I would like to compute the cross product of two vectors in Fortran 90. For example, in words, the cross product of (1, 2, 3) and (4, 5, 6) turns out to be (-3, 6, -3) in Cartesian coordinates. I wrote the following code (main program followed by function definition):
PROGRAM crosstest
IMPLICIT NONE
INTEGER, DIMENSION(3) :: m, n
INTEGER, DIMENSION(3) :: cross
INTEGER, DIMENSION(3) :: r
m=(/1, 2, 3/)
n=(/4, 5, 6/)
r=cross(m,n)
END PROGRAM crosstest
FUNCTION cross(a, b)
INTEGER, DIMENSION(3) :: cross
INTEGER, DIMENSION(3), INTENT(IN) :: a, b
cross(1) = a(2) * b(3) - a(3) * b(2)
cross(2) = a(3) * b(1) - a(1) * b(3)
cross(3) = a(1) * b(2) - a(2) * b(1)
END FUNCTION cross
But, I get an error message:
crosstest.f90:10.9:
r=cross(m,n)
1
Error: Rank mismatch in array reference at (1) (2/1)
where line 10 is r=cross(m,n). It seems that I must be specifying a dimension incorrectly. Here are a few ideas I have:
Perhaps the declaration of the function cross in the main program should be simply an integer variable, rather than a 1by3 integer array. So I tried deleting the , DIMENSION(3) in the INTEGER, DIMENSION(3) :: cross line in the main program. But I get an error message:
crosstest.f90:10.4:
r=cross(m,n)
1
Error: The reference to function 'cross' at (1) either needs an
explicit INTERFACE or the rank is incorrect
so this is even worse, probably.
Some (but not all) Fortran function examples on the web place an EXTERNAL statement after the function declaration in the main program. So I tried placing a line EXTERNAL cross after the declaration block in the main program. I get an error message:
crosstest.f90:8.16:
EXTERNAL cross
1
Error: EXTERNAL attribute conflicts with DIMENSION attribute at (1)
So this seems incorrect also.
Some (but not all) Fortran function examples on the web place a RETURN statement on the second-to-last line of the function definition. I tried this, but I get the original rank mismatch error:
crosstest.f90:10.9:
r=cross(m,n)
1
Error: Rank mismatch in array reference at (1) (2/1)
So this does not fix the problem.
Can you please help me see my error?
The best practice is to place your procedures (subroutines and functions) in a module and then "use" that module from your main program or other procedures. You don't need to "use" the module from other procedures of the same module. This will make the interface of the procedure explicit so that the calling program or procedure "knows" the characteristics of the arguments ... it allows the compiler to check for consistency between the arguments on both sides ... caller and callee .. this eliminates a lot of bugs.
Outside of the language standard, but in practice necessary: if you use one file, place the module before the main program that uses it. Otherwise the compiler will be unaware of it. so:
module my_subs
implicit none
contains
FUNCTION cross(a, b)
INTEGER, DIMENSION(3) :: cross
INTEGER, DIMENSION(3), INTENT(IN) :: a, b
cross(1) = a(2) * b(3) - a(3) * b(2)
cross(2) = a(3) * b(1) - a(1) * b(3)
cross(3) = a(1) * b(2) - a(2) * b(1)
END FUNCTION cross
end module my_subs
PROGRAM crosstest
use my_subs
IMPLICIT NONE
INTEGER, DIMENSION(3) :: m, n
INTEGER, DIMENSION(3) :: r
m= [ 1, 2, 3 ]
n= [ 4, 5, 6 ]
r=cross(m,n)
write (*, *) r
END PROGRAM crosstest
This is kind of a late answer, but since I stumbled upon this and there is no real explanation yet for why your error occurred, I figured I'd add an explanation for everybody else who stumbles upon this question:
In your program, you define an array called cross, which is of rank 1. Then you call the cross function you define further down. Since the cross function does not have an explicit interface (see M.S.B.'s answer), the compiler does not know about it at this point. What it does know about is the array you declared. If you write r = cross(m, n), the compiler thinks you want to access the element at position (m, n) of the array cross. Since this array is of rank 1, but you supplied two arguments, you get the error
rank mismatch in array reference at (1) (2/1)
which means that you supplied two coordinates when the compiler was expecting one.
You can place the subroutines used in a program after a contains keyword within the program. This eliminates the need for creating a module or adding the interface definition.
PROGRAM crosstest
IMPLICIT NONE
INTEGER, DIMENSION(3) :: m, n
INTEGER, DIMENSION(3) :: r
m = (/1, 2, 3/)
n = (/4, 5, 6/)
r = cross(m,n)
print *, r
CONTAINS
PURE FUNCTION cross(a, b)
INTEGER, DIMENSION(3) :: cross
INTEGER, DIMENSION(3), INTENT(IN) :: a, b
cross(1) = a(2) * b(3) - a(3) * b(2)
cross(2) = a(3) * b(1) - a(1) * b(3)
cross(3) = a(1) * b(2) - a(2) * b(1)
END FUNCTION cross
END PROGRAM crosstest
The complier interpretes the cross in your main program as an array, rather than a function name. Therefore cross in your main program has nothing to do with the function you defined. To let the compiler know that cross is a function name, you can just define in your main program:
INTEGER :: cross
Then, when the compiler see the line r=cross(m,n), the compiler know that this is not array indexing since cross is not defined as an array in the main program. Then a remaining possiblity is that this is a function call, and Fortran compiler ususally adopt this possiblity.
For your case, the compiler finds out that the cross function returns an array rather than a scalar. For this case, the compiler insists that you provide an explicit interface for cross. So this workaround does not work for your case. As other anwsers suggest, you need to provide an explicit interface by either
containing the function definition in a module and use that module in your main program
or
containing the function definition in your main program.
Fortran uses parentheses for both function call and array indexing.
This design often causes confusion because a programmer can not figure out f(3) is a function call or array indexing without additional information.
How do you check values in Fortran like in Matlab? For example in the little program under, why does it show c=0 in main when it is c=36 in the subroutine testing? How do you make it so c=36 in the main program?
Can you call on the value c in some sort of way? I understand that in the main program the variable c is either undefined or has value 0, but is there a way to save the value of c in the subroutine so you can use it again in other subroutines, without calculating it again?
When the program is quite large it is handy to check values as you go.
program main
use test
implicit none
integer :: a,b,c
call testing(a,b)
write(*,*)'Test of c in main program',c
end program main
module test
implicit none
contains
subroutine testing(a,b)
integer :: a,b,c
a=2
b=3
c=(a*b)**a
write(*,*)'Value of c in subroutine',c
end subroutine testing
end module test
It is important to learn about scope in programming languages.
Every name (identifier) has only a limited range of validity.
If you declare some variable inside a subroutine
subroutine s
integer :: i
end subroutine
than the i is valid only in that subroutine.
If you declare a variable in a module
module m
integer :: i
contains
subroutines and functions
end module
then the i is valid inside all those subroutines and functions and also in all program units that use that module.
However, that does not mean that you should declare the variable in the module and just share it. That would be more or less a global variable. This is reserved only for certain cases, where that is necessary, but not for getting results out of your subprograms.
If your subroutine just computes something and you want to get the result of that computation you have two possibilities:
1. pass it as an additional argument, which will be defined by the subroutine
subroutine testing(a, b, c)
integer, intent(in) :: a, b
integer, intent(out) :: c
c = (a*b) ** a
end subroutine
you then call it as
call testing(2, 3, c)
print *, "result is:" c
2. Make it a function
function testing(a, b) result(c)
integer, intent(in) :: a, b
integer :: c
c = (a*b) ** a
end function
and then you can use directly
c = testing(2, 3)
print *, "result is:", c
or just
print *, "result is:", testing(2, 3)
This is the desired behaviour. Basically the calling routine should know nothing about the subroutine except for how to call it and what to get back. This is called encapsulation.
You can make variables accessible to the calling routine by declaring it in the module itself, and not in the subroutine:
module test
implicit none
integer :: c
contains
subroutine testing(a, b)
implicit none
integer :: a, b
a = 2
b = 3
c = (a*b) ** a
write(*, *) "Value of c in the subroutine: ", c
end subroutine testing
end module test
program main
use test
implicit none
integer :: a, b
call testing(a, b)
write(*, *) "Test of c in the main program: ", c
end program main
Note that you must not declare c in the main program, as it will get the variable from the module.
You could also use a COMMON block, but modules are far superior.
Why am I in an infinite loop?
PROGRAM tayls
USE kertoma
USE tforexp
IMPLICIT NONE
INTEGER :: n= 5
INTEGER :: i
REAL :: x
WRITE(*,*) "f1(x)= (e**x-1)/x"
DO i=1,10
x= 0.01*i
WRITE(*,*)x, (taylexp(x,n)-1)/x
END DO
END PROGRAM tayls
with
MODULE tforexp
USE kertoma
IMPLICIT NONE
CONTAINS
FUNCTION taylexp(x,ord)
REAL :: taylexp, x, sum
INTEGER :: ord, i
sum= 1.0
DO i=1,ord
sum= sum+ x**i/fact(i)
END DO
taylexp= sum
END FUNCTION taylexp
END MODULE tforexp
and
MODULE kertoma
IMPLICIT NONE
CONTAINS
FUNCTION fact(n)
INTEGER :: fact,n,y=1
DO WHILE (n>1)
y= y*n
n= n-1
END DO
fact = y
END FUNCTION fact
END MODULE kertoma
The infinite loop starts right after the first print "f1(x)=...".
So I think it goes to infinite loop when calling the taylexp-function for the first time, but I don't understand why.
I think it has got something to do with fortran using public variables, but I'm clueless how to consistently avoid this.
First I tried to call the function without defining x, just using "0.01*i", and I thought maybe the problem was that this function used the same name for the dummy index, but it clearly it didn't solve the problem.
The problem is inside then function fact(n):
n= n-1
changes the argument and, therefore, the loop counter i in taylexp. In your code i never exceeds 2. I'm surprised the compiler didn't issue a warning (mine didn't either), because anything might happen in this case.
Better specify the intent of dummy arguments to avoid issues like this in the future:
FUNCTION fact(n)
integer,intent(in) :: n
INTEGER :: fact,nn,y
y=1 ! Avoid the implicit save and assign variables separately
nn=n
DO WHILE (nn>1)
y= y*nn
nn= nn-1
END DO
fact = y
END FUNCTION fact
With gfortran, it is possible to catch this error with
the -fcheck=all option:
$ gfortran -fcheck=all 1.f90
$ ./a.out
f1(x)= (e**x-1)/x
At line 22 of file 1.f90
Fortran runtime error: Loop variable has been modified
I'm new in Fortran. what's the problem with this simple code?
program combinatorial
Implicit none
integer :: m, n, Fact
integer :: Com
Write (*,*) 'inter 2 number for m and n'
Read (*,*) m,n
Com = Fact (m)/(Fact(n)*Fact(m-n))
Contains
integer Function Fact(t)
Implicit none
Integer, intent(IN) :: t
integer :: i, Ans
Ans = 1
Do i=1, t
Ans=Ans * i
End do
Fact = Ans
End Function Fact
End program combinatorial
The error that i encounter is :
combinatorial.f90(10): error #6626: The name of the internal procedure conflicts with a name in the encompassing scoping unit. [FACT]
integer Function Fact(t)
-------------------------^
compilation aborted for combinatorial.f90 (code 1)
Since Fact is contained within the program the compiler will generate an interface to it automatically. By also declaring an integer thing called Fact you're giving the compiler conflicting instructions and it don't like that. Just drop Fact from the line
integer :: m, n, Fact
The encompassing scoping unit referred to by the compiler is the program which contains (or encompasses) the function.
And, as an aside, you don't need to use the variable Ans in your definition of the function. You could simply write
integer Function Fact(t)
Implicit none
Integer, intent(IN) :: t
integer :: i
Fact = 1
Do i=1, t
Fact = Fact * i
End do
End Function Fact
Unless you use a result clause on the function statement the compiler will behave as if it creates a variable of the same name as the function for returning the function's result.