我一直在尝试使用泰勒系列创建一个可以计算辐射的 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
答案 0 :(得分:1)
我发现了四个错误: -
(1)事实应该设置为1 里面主DO循环
(2)事实应该在内部DO循环中乘以2n次
(3)在s的主要计算中,分母应该是事实,而不是事实* 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