各位fortran版的先进大家好
小弟我又来发问了
目前要计算fortran内建函数sin(x)的值
及利用泰勒级数展开的级数和(有限项)来计算sin值
且由使用者输入一计算精度
使两者的差值达到此精度
并输出泰勒级数需要几项才能达到
附上题目:
Write a Fortran program that:
Reads in a value of x in degrees and then calculates the sine of x using the
sine intrinsic function.
Next calculate the sine of x using above truncated infinite series to the
prescribed accuracy which is an input value. Be careful with how you evaluate
and sum up the terms.
Output the values of the sine of x calculated using both intrinsic function
and the truncated series, and the number of terms of the truncated series
required.
我的程式码如下:
program hw6
implicit none
real(kind=8) :: x !角度值
real(kind=8) :: sum=0.0 !利用truncated infinite series所计算的sin(x)
real :: temp=1.0 !用来使用阶乘
real(kind=8) :: e !误差值
integer :: precision !计算精度
integer :: i=1 !循环累加
!用来读取输入的角度和精度
write(*,*) "请输入角度:"
read(*,*) x
write(*,*) "请输入计算精度(准确至小数点后第几位):"
read(*,*) precision
!转换角度,使角度范围在0~360度
if(x>=0) then
x=x-real(floor(x/360.0))*360.0
else
x=x+real(floor(abs(x)/360.0)+1)*360
end if
!转换角度,使角度范围在-90~90度
if(x<=90) then
x=x
else if(x<=270) then
x=180-x
else
x=x-360
end if
write(*,*) "转换后的角度=",x
x=x*acos(-1.0)/180.0 !角度转换为径度
e=10.0**(-1.0*real(precision)) !设定期望误差值
sum=sum+x !先设定The truncated series的第一项
!利用循环来计算sum of the truncated series
!当级数和和内建函数sin(x)的误差小于等于期望误差值e时,跳出循环
do
i=i+1
temp=temp/(real(2*i-1)*real(2*i-2))
sum=sum+(-1.0)**real(i-1)*temp*x**real(2*i-1)
write(*,*) "级数前",i,"项之和=",sum
if(abs(sin(x)-sum)<=e) exit
end do
write(*,*) "sin(x)=",sin(x) !内建函数计算之结果
write(*,*) "sum of sine truncatd series=",sum !级数计算之结果
write(*,*) "需要",i,"项" !级数需要之项数
stop
end
目前的问题是如果角度的输入值过大(例如输入13位数的值)
或是精度过高(例如误差要计算到小数点后第九位)
都会无法达成跳出循环的条件
甚至出现NAN的值
想请教各位
此问题是否有解?
感谢!