[問題] 關於計算精度?

看板Fortran作者 (crossstep)時間9年前 (2014/10/12 23:16), 編輯推噓1(104)
留言5則, 3人參與, 最新討論串1/1
各位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://www.ptt.cc/bbs/Fortran/M.1413127013.A.61A.html

10/13 20:18, , 1F
先觀察無法跳出迴圈的原因。觀察每次的結果,應該就能
10/13 20:18, 1F

10/13 20:19, , 2F
看出端倪。另外類似這種迴圈,建義都設一個最大跌代次數
10/13 20:19, 2F

10/13 20:20, , 3F
的限制,避免程式掛在那邊。
10/13 20:20, 3F

10/13 22:20, , 4F
跑不完 => 跟收斂特性有關, nan => 跟值有關係
10/13 22:20, 4F

10/14 18:57, , 5F
感謝兩位的回覆 我再研究一下
10/14 18:57, 5F
文章代碼(AID): #1KEfjbOQ (Fortran)