Reputation: 7435
I am new to Fortran. I am facing a weird problem and I don't know how to troubleshoot this. I have pasted the minimum working code to demonstrate the problem below.
In the code everything works except the cosine
function call. It is giving wrong results. The most weird thing is the result changes if I uncomment the commented line below (which is in no way related to the returned value).
(As I've read in several SO questions this looks like a results of an invalid memory access, but couldn't figure anything out)
program prog
implicit none
double precision, dimension(2) :: vec1 = (/ 3, 4 /)
double precision, dimension(2) :: vec2 = (/ 4, 3 /)
print *, inner_product(2, vec1, vec2)
print *, norm(2, vec1)
print *, cosine(2, vec1, vec2)
contains
double precision function inner_product(N, V1, V2)
integer, intent(in) :: N
double precision, dimension(*), intent(in) :: V1
double precision, dimension(*), intent(in) :: V2
integer :: i
do i = 1, N
inner_product = inner_product + V1(i)*V2(i)
end do
end function inner_product
double precision function norm(N, V)
integer, intent(in) :: N
double precision, dimension(*), intent(in) :: V
norm = sqrt(inner_product(N, V, V))
end function norm
double precision function cosine(N, A, B)
integer, intent(in) :: N
double precision, dimension(*), intent(in) :: A
double precision, dimension(*), intent(in) :: B
double precision :: na
! na = norm(N, A)
cosine = inner_product(N, A, B) / (norm(N, A) * norm(N, B))
end function cosine
end program prog
UPDATE:
Running the posted code gives the following result,
24.000000000000000
5.0000000000000000
0.67882250993908555
Running the program after uncommenting the currently commented line gives the following,
24.000000000000000
5.0000000000000000
0.39191835884530846
None of them are true. The expected result is 0.96
(which is given by 24 / (5*5))
.
Upvotes: 1
Views: 147
Reputation: 974
Your problem is that gfortran doesn't detect your error unless optimization is in force:
D:\gfortran\clf\uninit>gfortran -O2 uninit.f90 -ouninit
D:\gfortran\clf\uninit>gfortran -Wall uninit.f90 -ouninit
uninit.f90:31:28:
double precision :: na
1
Warning: Unused variable 'na' declared at (1) [-Wunused-variable]
D:\gfortran\clf\uninit>gfortran -O2 -Wall uninit.f90 -ouninit
uninit.f90:31:28:
double precision :: na
1
Warning: Unused variable 'na' declared at (1) [-Wunused-variable]
uninit.f90:17:0:
inner_product = inner_product + V1(i)*V2(i)
Warning: '__result_inner_product' is used uninitialized in this function [-Wunin
itialized]
It's this last error you want to encourage gfortran to detect.
Upvotes: 1