Re: Floating point: sine, cosine etc.

From: Michal Pleban <lists_at_michau.name>
Date: Fri, 23 Sep 2022 22:48:17 +0200
Message-ID: <3250ee92-9d0f-0fa8-a8d4-16e5c45bf8df_at_michau.name>
ruud_at_baltissen.org wrote on 23.09.2022 22:01:

> On Wikipedia I found something: 
> https://en.wikipedia.org/wiki/Sine_and_cosine#Series_definitions . But I 
> did not know what to think of it, technically spoken I could turn these 
> formulas into code but how cycle hungry would such a solution be? So I 
> turned to the source code of C64's Basic and ended up with polynomes. 
> Difficult stuff, I must say.
	
In the Wikipedia article, I see a simple solution with this polynomial:

https://wikimedia.org/api/rest_v1/media/math/render/svg/def345e147219a7892eb8140dfeb1c77b29dce38

Basically, it amounts to something like this for SIN(X):

S = X  : REM RESULT
Z = 1  : REM SIGN
P = X  : REM POWER
F = 1  : REM FACTORIAL
FOR I = 3 TO [SOME_LIMIT] STEP 2
   P = P * X * X
   F = F * (I - 1) * I
   Z = -Z
   S = S + Z * P / F
NEXT I

You have a number of multiplications and divisions in each step, they 
are a bit cycle hungry when done on floating point numbers, but not 
overly so.

Everything of course depends on how many steps the loop is going to be 
run for. The more steps, the more accurate the result, but also the more 
CPU cycles.

Also, from the pictures in the Wikipedia article, it is clear that you 
need to limit X to the range of [-PI, PI], as the sinus function is 
periodical and the polynomial has the best accuracy in this range. If X 
is from outside this range, reduce it accordingly (this most likely 
requires another division and multiplication).

Regards,
Michau.
Received on 2022-09-23 23:03:47

Archive generated by hypermail 2.3.0.