Calculate sine and cosine functions with precision

How to calculate sine and cosine functions with some precision in java?

Since the standard sin

and cos

do not allow this.

+1


source to share


2 answers


You can use the Taylor series sin and cos expansion to calculate arbitrary precision:

enter image description here



enter image description here

+9


source


The Taylor expansion (or, more precisely, the Maclaurin expansion, which is Taylor around x = 0) is not a good way to do this calculation. Most computers use the CORDIC algorithm - it has the advantage of converging to arbitrary precision in a finite number of iterations and only requires very simple math.

Another thing to keep in mind: you really want to start with the exact way to decrease the parameter x

to be in the range [0 pi / 2], taking care of the sign of the answer using simple logic, When x gets large, the Maclauren (Taylor) extension will fluctuate for a very long time.

This means, among other things, that you need to know the value pi

at least up to the number of digits of your desired answer, plus how many more digits you would need to decrease x

(because if x = 1,000,000, you need 6 more digits of pi to get answer with sufficient accuracy in the reduced domain).



Ultimately you will have fewer digits of precision in your result than the precision of your calculations - according to the source above, with 64-bit doubles your number with 48 iterations of the algorithm (precision approximately 1 in 2 ^ 48). Since the value for double is 53 bits, this is actually not too bad (within 5 bits of precision used in the calculation).

A java implementation of the algorithm can be found in this earlier answer . It would be interesting to see how it compares to the Taylor expansion ...

EDIT This article compares the convergence of the CORDIS and Taylor extension and concludes that Taylor is faster when you work in the recovered domain (so after casting x to [0 pi / 2]). It also has a pretty neat reformulation that gets around a lot of round-off errors - making it more accurate than a rough estimate of the conditions.

+11


source







All Articles