我写了一个子程序来计算二项式系数(n选择k),它将用于n和中等k值的大值(因此接近给定n的最大值)。子程序代码是FORTRAN 95准确度很大的除法
!
! Subroutine to calculate combinatoric term (n choose x)
!
subroutine COMBO(m,y,combin)
implicit none
integer m,y,b1,b2,maxx,minn
real (kind=16) combin,temp1,temp2
temp1 = real(1,16)
temp2 = real(1,16)
maxx = MAX(y,m-y)
minn = MIN(y,m-y)
do b1 = maxx+1,m
temp1 = temp1*real(b1,16)
enddo
do b2 = 1,minn
temp2 = temp2*real(b2,16)
enddo
combin = temp1/temp2
end subroutine COMBO
这适用于中等大的值。但是,如果我用N = 100和K = 55我得到以下
61448471214136179596720592959.998
小数部分显然是错误的,因为组合总是整数。主程序是
program chkint
implicit none
integer i,j,n,k
real (kind=16) cmb
print*,"what is n?"
read*,n
print*,"what is k?"
read*,k
call combo(n,k,cmb)
print*,cmb
end
顺便说一句:kind = 16是我的机器上的四倍精度。
感谢
你使用什么编译器?我得到了'61448471214136179596720592960.0000'这是一个预期的答案。小数点在那里是因为'cmb'是真实的。你得到的是由于浮点计算而导致的错误。 – Cheery 2014-10-11 01:15:05
感谢您的回答。我正在使用Absoft FORTRAN 95.如果我将cmb声明为整数,它根本不起作用。有什么我可以做的关于浮点计算的错误吗? – DrBenway 2014-10-11 01:33:56
我没有它,用过英特尔的。它也可能取决于x86或x64 OS/CPU。如果你有x64编译器和系统 - 为什么不使用'selected_int_kind(32)' – Cheery 2014-10-11 01:35:36