Reasonably Optimised Sin and Cos Functions for Picaxe

Armp

Senior Member
I've recently mapped my 1990s vintage HC11 sin/cos approximation over to Picaxe 20M2 and figured it may be of interest. I used a combination of series expansions, Chebyshev polynomials and a bit of fine tuning.

The code is about 115 bytes and gives 3+ significant figures over most of the range 0.0 - 90.0 degrees.

The program below is a small demo, producing comma delimited results, to check accuracy against Excel.

I hope it demonstrates the you can do some pretty serious number crunching with Picaxe's 16bits.

Code:
Symbol LoopCnt = w11        ' Used in Demo Code.
Symbol X        = w12
Symbol Temp    = w13

Symbol StringBuf = $60        ' 32 byte buffer starts here
Symbol StackX    = $40        ' Save X reg

SinCosTest:

For LoopCnt= 0 to 900 step 50[INDENT]X=loopcnt :  Gosub PrintX
Gosub SinX :  Gosub PrintX
X=loopcnt
Gosub CosX : Gosub PrintX
serout b.1,N2400,(13)     '  b.1 for Simulator
Next Loopcnt
[/INDENT]
 Stop
 
PrintX:         'Comma delimited for pasting into Excel
Bptr = StringBuf
bintoascii X,@bptrinc,@bptrinc,@bptrinc,@bptrinc,@bptrinc  
Bptr = StringBuf
serout b.1,N2400,(@bptrinc,@bptrinc,@bptrinc,@bptrinc,@bptrinc,", ")
Return 

'End of Test Prog

' ***************************************************
' Subroutine Uses Sin(x) = 1.743*X - 0.00000085*X^3
' Calculation scaled for X in 1/10 Degrees. .
' ***************************************************

SinX:
If X>450 Then : X=900 - X: Goto CosX : Endif ' 0 <= X <= 450   
Temp = X*100**57120             
X = X/4*X/25*17+200/400*X+5/10    
X = Temp - X /5                   ' X = 10000*Sin(X)  
Return

' ***************************************************
' Subroutine Uses Cos(x) = 1 - 0.3092X - 0.13899*X^2
' And Cos(x) = 1 - 0.5*X^2 for small values of X
' Calculation scaled for X in 1/10 Degrees.
' ***************************************************

CosX:   
If X>450 Then : X=900 - X : Goto SinX : Endif
If X < 65 Then : X = X*X + 33 /66: X = 10000 - X: Else[INDENT]Temp = x/2                       ' 0 <= X <= 450   
Temp= Temp * Temp ** 21705                 
X = 13*X/7
X = 60000 - X - Temp/6        ' X = 10000*Cos(X/10) 
[/INDENT]
 EndIf
Return
Here are the Simulator test results compared to Excel:

DegreesSinXSin(X)CosXCos(X)
0001000010000
5087087299629962
1001735173698319848
1502587258896439659
2003418342093869397
2504227422690609063
3005001500086658660
3505737573682018192
4006428642876687660
4507070707170667071
5007668766064286428
5508201819257375736
6008665866050015000
6509060906342274226
7009386939734183420
7509643965925872588
8009831984817351736
85099629962870872
900100001000000
 
Last edited:
Top