【问题标题】:Write Newton binomial in Fortran90在 Fortran90 中编写牛顿二项式
【发布时间】:2013-10-19 05:27:52
【问题描述】:

我必须在 Fortran 中编写一个返回牛顿二项式结果的脚本: for a, b and n given.

问题是我不能使用函数或子程序。

到目前为止,我已经编写了组合代码:

    if (n==0) then
        print*, "Cnk=",Cnk
else if ((n>=0).and.(k==0)) then
        print*, "Cnk=",Cnk
else
        do i=1,n,1
                aux=aux*i

                if (k==i) then
                        factK=aux
                end if

                if ((n-k)==i) then
                        factnk=aux
                end if

                factn=aux
        end do

        Cnk=factn/(factk*factnk)

        print*, "Cnk=",Cnk

end if

在二项式的情况下,k 是从 0 到 n 的变量。

【问题讨论】:

    标签: fortran


    【解决方案1】:

    可能不是最快的解决方案,但很短:

    program binom
    
      implicit none
      integer,parameter :: N=5
      integer,parameter :: a=3
      integer,parameter :: b=5
      integer           :: k, i
      integer           :: coeff, eval, total
    
      total = 0 
      do i=0,N
        coeff = product((/ (k,k=1,n) /)) / product((/ (k,k=1,i),(k,k=1,n-i) /))
        eval  = coeff * a**(n-i) * b**i
        total = total + eval
        write(*,*) 'i=',i,'coeff=',coeff, 'eval=',eval
     enddo !i
     write(*,*) '(a+b)**n=',(a+b)**N,'Total=',total
    
    end program binom
    

    输出:

     i=           0 coeff=           1 eval=         243
     i=           1 coeff=           5 eval=        2025
     i=           2 coeff=          10 eval=        6750
     i=           3 coeff=          10 eval=       11250
     i=           4 coeff=           5 eval=        9375
     i=           5 coeff=           1 eval=        3125
     (a+b)**n=       32768 Total=       32768
    

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 2018-11-21
      • 2017-06-28
      • 1970-01-01
      • 2013-12-26
      • 2013-05-06
      • 2014-07-11
      • 1970-01-01
      • 2013-10-17
      相关资源
      最近更新 更多