C++ (and maths) : fast approximation of a trigonometric function

后端 未结 7 1292
野的像风
野的像风 2020-12-30 04:52

I know this is a recurring question, but I haven\'t really found a useful answer yet. I\'m basically looking for a fast approximation of the function acos in C+

7条回答
  •  再見小時候
    2020-12-30 05:29

    sin( acos(t1) + acos(t2) + ... + acos(tn) )
    

    boils down to the calculation of

    sin( acos(x) ) and cos(acos(x))=x
    

    because

    sin(a+b) = cos(a)sin(b)+sin(a)cos(b).
    

    The first thing is

    sin( acos(x) )  = sqrt(1-x*x)
    

    Taylor series expansion for the sqrt reduces the problem to polynomial calculations.

    To clarify, here's the expansion to n=2, n=3:

    sin( acos(t1) + acos(t2) ) = sin(acos(t1))cos(acos(t2)) + sin(acos(t2))cos(acos(t1) = sqrt(1-t1*t1) * t2 + sqrt(1-t2*t2) * t1
    
    cos( acos(t2) + acos(t3) ) = cos(acos(t2)) cos(acos(t3)) - sin(acos(t2))sin(acos(t3)) = t2*t3 - sqrt(1-t2*t2)*sqrt(1-t3*t3)
    
    sin( acos(t1) + acos(t2) + acos(t3)) = 
    sin(acos(t1))cos(acos(t2) + acos(t3)) + sin(acos(t2)+acos(t3) )cos(acos(t1)=
    sqrt(1-t1*t1) * (t2*t3 - sqrt(1-t2*t2)*sqrt(1-t3*t3)) + (sqrt(1-t2*t2) * t3 + sqrt(1-t3*t3) * t2 ) * t1
    

    and so on.

    The sqrt() for x in (-1,1) can be computed using

    x_0 is some approximation, say, zero
    
    x_(n+1) = 0.5 * (x_n + S/x_n)  where S is the argument.
    

    EDIT: I mean the "Babylonian method", see Wikipedia's article for details. You will need not more than 5-6 iterations to achieve 1e-10 with x in (0,1).

提交回复
热议问题