Re: Floating point: sine, cosine etc.

From: ruud_at_baltissen.org
Date: Wed, 28 Sep 2022 21:21:16 +0200
Message-ID: <5d3e45357cf8c80348f7afb9e8a7a96b_at_baltissen.org>
Hallo MichaƂ,


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

I found the page containing the above formula and through that run into 
https://en.wikipedia.org/wiki/Horner%27s_method .

This let to:


var
   arFacCos,
   arFacSin      : array[0..15] of real;
   arFactorial   : array[1..15] of real;

   b, i, l       : byte;
   s, z, p, f, x : real;


{ Create factorial number }
function Fac(b : byte) : real;
var
   t : byte;
   r : real;
begin
   r := 1;
   for t := 2 to b do r := r * t;
   Fac := r;
end;


begin
   writeln(sin(x));


{ Create arrays }
   for b := 1 to 15 do arFactorial[b] := Fac(b);

   arFacSin[0] := 0;
   arFacSin[1] := 1 / arFactorial[1];
   arFacSin[2] := 0;
   arFacSin[3] := -1 / arFactorial[3];
   arFacSin[4] := 0;
   arFacSin[5] := 1 / arFactorial[5];
   arFacSin[6] := 0;
   arFacSin[7] := -1 / arFactorial[7];
   arFacSin[8] := 0;
   arFacSin[9] := 1 / arFactorial[9];
   arFacSin[10] := 0;
   arFacSin[11] := -1 / arFactorial[11];
   arFacSin[12] := 0;
   arFacSin[13] := 1 / arFactorial[13];
   arFacSin[14] := 0;
   arFacSin[15] := -1 / arFactorial[15];



   p := 1;
   s := arFacSin[0];

   for b := 1 to 15 do
    begin
     p := p * x;
     s := s + arFacSin[b] * p;
    end;

   writeln(s);



{ Horner }
   s := (arFacSin[15] * x) + arFacSin[14];

   for b := 13 downto 0 do
    begin
     s := arFacSin[b] + x * s;
    end;

   writeln(s);

end.


The idea is to use tables instead of calculating the various factors. In 
the final assembly version this will constants in FP format, not 
variables. That reduces your formula to the first FOR loop.
Knowing, thanks to you, where to look for, I found Horner's method which 
reduced the FOR loop even further. I even can reduce the number of steps 
by skipping those steps where arFacSin[b] is zero (plus some other 
needed changes).

Next step is tangens. I found the formula but here I ran into trouble: 
https://en.wikipedia.org/wiki/Trigonometric_functions#Power_series_expansion 
. The formula includes Bernoulli numbers and from here on I couldn't 
follow it anymore. I could use the method GWBASIC uses: calculate SIN(x) 
and divide it by COS(x) but that involves too many calculations IMHO. 
But suddenly I realized that I have a neighbor who is bachelor in 
mathematics, my own son. I asked him and he will look at these this and 
will either produce an end formula or give me a table with these 
numbers.

Next steps: EXP, LN, LOG, etc., etc. But know I know on who's door to 
knock :)


-- 

Kind regards / Met vriendelijke groet, Ruud Baltissen

www.Baltissen.org
Received on 2022-09-28 22:00:03

Archive generated by hypermail 2.3.0.