-2

我一直在尝试创建一个可以使用泰勒级数计算辐射的cos的程序。我考虑了这个错误,例如:

cos(45)=1.4一定是这样的: s=(((-1.)**n/(fact*2.*n))*x**(2.*n))*sign

编码:

program project2_ex6
implicit none
!Reference to variables
!-------------------------------------------------------
integer(kind=3)::degrees,i,sign !sign=a random name in order to use it to change the 's' sign consecutively
integer::n
double precision::x,err_limit,s_old,s,fact !x=angle in radiants,err_limit=the absolute error between two results,fact=factorial
real,parameter::pi=3.14159265359
!------------------------------------------------------
print*,'This program calculates the cos(x)'
print*,"Enter the angle's degrees"
read*,degrees
!Checking validity of degrees
!----------------------------------------------------
do
if(degrees<0.or.degrees>360) then
  print*,'Degrees must be between 0-360'
  else
   x=pi*degrees/180
    exit
    end if
    end do
    sign=1
    sign=sign*(-1)
    err_limit=1e-5
 n=0
    s=0
    s_old=0
    fact=1
!Commencing do loop
!-----------------------------------------------------------
do
  do i=1,n
    fact=fact*i
    end do
    if(n==0) then
      s=1
      else
  s=(((-1.)**n/(fact*2.*n))*x**(2.*n))*sign
 s=s+s_old
end if
n=n+1
if(abs(s-s_old)<err_limit) then
  exit
  else
    s_old=s
    cycle
    end if
  end do
  !Printing results
!-----------------------------------------------------------------
  print*,s,i,n
  end program
4

1 回答 1

1

我发现了四个错误:-

(1) fact 应该在主 DO 循环内设置为 1

(2) fact 应该在内部 DO 循环中乘以自身 2n 次

(3)在s的主要计算中,分母应该是fact,而不是fact*2*n

(4)在s的主要计算中,不需要乘以符号(或者如果你这样做,它应该是+1)

这现在给出 0.7071... 45 度。

program project2_ex6
implicit none
!Reference to variables
!-------------------------------------------------------
integer::degrees,i,sign !sign=a random name in order to use it to change the 's' sign consecutively
integer::n
double precision::x,err_limit,s_old,s,fact !x=angle in         radiants,err_limit=the absolute error between two results,fact=factorial
real,parameter::pi=3.14159265359
!------------------------------------------------------
print*,'This program calculates the cos(x)'
print*,"Enter the angle's degrees"
read*,degrees
!Checking validity of degrees
!----------------------------------------------------
do
 if(degrees<0.or.degrees>360) then
  print*,'Degrees must be between 0-360'
 else
   x=pi*degrees/180
    exit
  end if
end do
    sign=1
!
! Sign should be +1 or omitted
!
!-   sign=sign*(-1)
 err_limit=1e-5
 n=0
 s=0
 s_old=0

!Commencing do loop
!-----------------------------------------------------------
do
!
! Initialise fact inside do loop
!
  fact=1
!
! Change n to 2n
!
  do i=1,2*n
    fact=fact*i
   end do
  if(n==0) then
     s=1
  else
!
!Change fact*2*n to fact
!
    s=(((-1.)**n/(fact))*x**(2.*n))*sign
    s=s+s_old
  end if
 n=n+1
 if(abs(s-s_old)<err_limit) then
  exit
 else
    s_old=s
    cycle
    end if
end do
  !Printing results
!-----------------------------------------------------------------
 print*,s,i,n
 end program
于 2015-11-22T11:28:51.037 回答