使用MacLaurin扩展的Fortran Sine功能的细微差别 [英] Small difference in Fortran Sine function using MacLaurin expansion
问题描述
我正在Fortran中创建一个程序,该程序以弧度表示sin(x)的x,然后是要计算的项数.
I'm creating a program in Fortran that takes in an x for sin(x) in radians, then the number of terms to compute.
这是我的程序:
! Sine value using MacLaurin series
program SineApprox
implicit none
integer :: numTerms, denom, i
double precision :: x, temp, summ
! Read Angle in Radians, and numTerms
read(*,*) x, numTerms
! Computing MacLaurin series
denom = (2*numTerms)-1 !Gives denominator
temp = x !Temp calculates each term
summ = x
do i = 3, denom, 2
temp = (((-temp)*(x**2))/(i*(i-1)))
summ = summ + temp
end do
print *, summ
end program SineApprox
但是,我没有获得教授输入所需的值:5 30
However, I'm not getting the same value that my prof requires for the input: 5 30
我的代码的输出是:
-0.95892427466314001
但是,所需的输出是:
-0.95892427466313568
^^^^
我不知道错误在哪里.
I can't figure out where the error is.
推荐答案
我不知道错误在哪里.
I can't figure out where the error is.
高精度sine(5.0)
是-0.95892427466313846889...
OP的结果要比Prof的要好.
OP’s result is better than Prof’s.
OP的结果在最佳答案的14 ULP 之内,而教授的折扣为25 ULP.
OP's result is within 14 ULP of the best answer whereas Prof's is 25 ULP off.
因此,OP方面没有问题.要使精确与教授的答案完全匹配,您必须编写劣等方法.
So no problem on OP’s part. To get an exact match to the Prof's answer, you would have to code an inferior approach.
教授的次等答案的一个简单可能的原因是,教授的代码是否仅在i<=30
(15个术语,而不是30个术语)时才循环-只能解释差异.尝试以较少的迭代次数使用您的代码,看看哪些迭代次数最接近Prof的答案.
A simple possible reason for the Prof's inferior answer is if Prof's code looped only while i<=30
(15 terms, rather than 30) - which would just about explain the difference. Try using your code with fewer iterations and see what iteration count closest matches the Prof's answer.
// sine(5.0) Delta from correct Source
//
//-0.95892427466313846889... 0 000000 calc
//-0.95892427466313823 -23 889... chux (via some C code)
//-0.95892427466314001 +154 111... OP
//-0.95892427466313568 -278 889... Prof
// 0.00000000000000089 +/-89 ... ulp(5.0)
// 0.00000000000000011 +/-11 ... ulp(-0.9589)
// 12345678901234567(digit count)
注意:
在x == 5.0
附近,大约在第17项之后,temp
项是如此之小,以至于不会显着影响结果.因此可以肯定使用了足够的术语.
Notes:
Near x == 5.0
, after about the 17th term, the temp
term is so small to not significantly affect the result. So certainly enough terms are used.
使用通用FP表示法,最后5位的单位为〜89e-17.如果为〜11e-17,则ULP为-0.9589.
With common FP representation, the unit in the last place of 5 is ~89e-17. The ULP of -0.9589 if is ~11e-17.
这篇关于使用MacLaurin扩展的Fortran Sine功能的细微差别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!