作者screase (crossstep)
看板Fortran
标题[问题] 关於计算精度?
时间Sun Oct 12 23:16:51 2014
各位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的值
想请教各位
此问题是否有解?
感谢!
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.112.233.49
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/Fortran/M.1413127013.A.61A.html
1F:推 sin55688: 先观察无法跳出回圈的原因。观察每次的结果,应该就能 10/13 20:18
2F:→ sin55688: 看出端倪。另外类似这种回圈,建义都设一个最大跌代次数 10/13 20:19
3F:→ sin55688: 的限制,避免程式挂在那边。 10/13 20:20
4F:→ charlesdc: 跑不完 => 跟收敛特性有关, nan => 跟值有关系 10/13 22:20
5F:→ screase: 感谢两位的回覆 我再研究一下 10/14 18:57