指数泰勒级数的问题

  • 本文关键字:问题 指数 fortran
  • 更新时间 :
  • 英文 :


我在准确运行此代码时遇到问题,代码编译正确,但对于我为 inputsin输入的每个值,我将始终收到 1.0 作为答案。

指数的泰勒级数将通过定义从 1 开始。 我的阶乘实现可能不正确,但对阶乘循环的任何编辑都会呈现看似无限循环的内容。

program taylor
    implicit none
    real :: inputexp, inputsine  ! The values of input for the arguments of the taylor series
    real :: exptaylor, sinetaylor ! The value of the sine and exponential calculated
    real :: expseries, sineseries ! The value found by the taylor series
    real, parameter :: accuracy = 1.e-10  ! The value of accuracy
    integer :: NN, aa, bb, cc, dd, ee, ff, gg, hh ! Loop indices and factorial things
    integer:: nfactexp ! Factorial for the exponential series
    integer :: Nexp ! Number of turns
    write(*,*) "Write the value of the input of the exponential taylor series"
    read(*,*) inputexp

    ! Calculating the exponential function using taylor series
     exptaylor = 1 ! Initializing the exponential function taylor arguemnts

    ! Loop to calculate the exponential function
    aa = 0
    do while(abs(exptaylor) > accuracy)
        ! Computing factorial
        nfactexp = 1 ! Accounting for 0!=1
        do bb = 1, aa
            nfactexp = nfactexp*bb
        enddo
        ! Evaluating the series
        aa = aa+1
        exptaylor = (inputexp**aa)/nfactexp
        expseries = exptaylor + expseries

        enddo
        Write(*,*) "The number of terms of the series, N", aa
        Write(*,*) "The value of the exponential according to the taylor series", expseries
    end program

你有几个问题。

首先,您没有初始化expseries.您应该在循环之前设置它。现在,结果完全是任意的,因为expseries的初始值是不确定的。

其次,您的变量nfactexp溢出。 您可能正在使用的 32 位整数最多只允许数字 2 147 483 647。此外,(inputexp**aa)可能会溢出。虽然不能使用有限数量的位修复所有输入的溢出,但可以扩展可计算区域。通过使用最后一个expterm计算每个,如expterm = expterm / aa * inputexp,您可以获得最大的范围。

上面的更改还意味着您不再冗余地计算阶乘项,并将幂减少为乘法,从而使代码也更快。

此外,while循环条件上的abs是不必要的,因为expterm始终是非负数。

请参阅下面的代码:

program taylor
    implicit none
    real :: inputexp, exptaylor, expseries
    real, parameter :: accuracy = 1.0e-10
    integer :: aa
    write(*,*) "Write the value of the input of the exponential taylor series"
    read(*,*) inputexp
    exptaylor = 1  ! The first term is constant
    expseries = 1  ! The first term is already included
    aa = 0  ! Term index, i.e. 0 for the constant
    do while (exptaylor > accuracy)
        aa = aa + 1
        ! Use the previous value of exptaylor.
        ! Just scale it with the one more inputexp to get the x**n
        ! correct, and divide by aa for the factorial.
        exptaylor = exptaylor / aa * inputexp
        expseries = exptaylor + expseries
    enddo
    Write(*,*) "The number of terms of the series, N", aa
    Write(*,*) "The value of the exponential according to the taylor series", expseries
end program

最新更新