指数泰勒级数的问题

时间:2019-06-18 03:06:51

标签: fortran

我在准确运行此代码时遇到问题,代码可以正确编译,但是对于输入的每个输入值,我总是会收到1.0作为答案。

指数的泰勒级数将按定义从一个开始。我的阶乘实现有可能是不正确的,但是对阶乘循环的任何编辑都会呈现出无限循环。

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

1 个答案:

答案 0 :(得分:2)

您有几个问题。

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

第二,您的变量nfactexp溢出。您可能正在使用的32位整数只允许使用最大2147483647的数字。而且,(inputexp**aa)可能会溢出。虽然无法使用有限的位数修复所有输入的溢出,但是可以扩展可计算区域。通过使用最后一个expterm计算每个expterm = expterm / aa * inputexp,您可以获得最大的范围。

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

此外,abs循环条件下的while也是不必要的,因为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