I am having an issue with a very simple Fortran 90 program. I am calculating three combinations and using a declared Double Precision function to do the calcs and return the results. At present the numbers are quite small, and I have declared the Function as double precision, but I may wish to go to Quad precision in future. I have added some Write(,) statements in my Function to show stages of the calculations as part of the program development and error checking.
The issue I am having is that on compiling the program, I am getting Error: Return type mismatch of function ‘cnk’ at (1) (REAL(8)/REAL(4) for each of the three calls of CNK.
My simple program is:
PROGRAM CNKtest
IMPLICIT NONE
integer, parameter :: dp = selected_real_kind(15,307)
integer, parameter :: qp = selected_real_kind(33,4931)
integer :: a,b,c,d,e
real (kind=dp) :: CNK
a = 90
b = 910
c = 50
d = 1000
e = 0
open(22,file='CNKTest.csv',STATUS='new')
write(22,405) (CNK(a,e)*CNK(b,c)/CNK(d,c))*100
405 format (f5.2,‘,’)
END PROGRAM CNKtest
REAL FUNCTION CNK (n,k) ! Combinations formula
IMPLICIT NONE
integer :: i,n,k ! n = sample size, k = choices
integer, parameter :: dp = selected_real_kind(15,307)
integer, parameter :: qp = selected_real_kind(33,4931)
real (kind=dp) :: tmp
tmp = 1
write(*,*) n,k
if (k==0) then ! k = 0 combination of no choices
CNK = 1
else if (k>0) then
do i = 1,k
tmp = (REAL(n-(i-1))/REAL(i))*tmp
end do
end if
CNK = tmp
write(*,*) tmp,cnk
END FUNCTION CNK
If I declare CNK as single precision (e.g. real :: CNK), it compiles without error, and calculates ‘tmp’ without any issue, but on the handover to CNK (e.g. CNK = tmp), I get CNK = Infinity and Not a Number ‘NaN’ output to my .csv file - as I expected given single precision is not sufficient for the numbers I am using. I am using the MinGW compiler with simple compile comment -o e.g. CNKTest.f90 -o CNKText.exe.
Any help would be gratefully received.