Author: John Pears
How to really speed up sine and cosine calculations
Answer:
If you have ever written applications that require many sine and cosine
calculations over a short time you will have realized that things really start to
slow down.
This is an old trick. But if you have never come across it, it really is worth
using.
This version uses degrees not radians.
1 unit sin_Tool;
2 3 interface4 const5 FULL_CIRCLE = 360;
6 HALF_CIRCLE = 180;
7 // TEN_CIRCLES = 3600;8 function MySin(x: integer): real; overload;
9 function MySin(x: real): real; overload; // allow both reals or integers10 11 function MyCos(x: integer): real; overload;
12 function MyCos(x: real): real; overload; // allow both reals or integers13 14 { ===================================================== }15 { ===================================================== }16 implementation17 18 uses19 Math;
20 const21 MULTIPLIER = 10;
22 NUM_ELEMENTS = FULL_CIRCLE * MULTIPLIER;
23 type24 tArcAnswers = array[0..NUM_ELEMENTS] of real;
25 var26 SinResults,
27 CosResults: tArcAnswers;
28 { =====================================================29 function DegToRad(x:real):real; // OK... no need .. its in the math unit...30 ===================================================== }31 32 procedure InitArcAnswers;
33 var34 c: integer;
35 begin36 for c := 0 to NUM_ELEMENTS do37 begin38 SinResults[c] := sin(DegToRad(c / MULTIPLIER));
39 CosResults[c] := cos(DegToRad(c / MULTIPLIER));
40 end;
41 c := 1;
42 end;
43 { ===================================================== }44 45 function MySin(x: integer): real; overload;
46 begin47 while (x > FULL_CIRCLE) do48 x := x - FULL_CIRCLE;
49 while (x < 0) do50 x := x + FULL_CIRCLE;
51 52 Result := SinResults[x * MULTIPLIER];
53 end;
54 55 function MySin(x: real): real; overload;
56 begin57 while (x > FULL_CIRCLE) do58 x := x - FULL_CIRCLE;
59 while (x < 0) do60 x := x + FULL_CIRCLE;
61 Result := SinResults[round(x * MULTIPLIER)];
62 end;
63 { ===================================================== }64 65 function MyCos(x: integer): real; overload;
66 begin67 while (x > FULL_CIRCLE) do68 x := x - FULL_CIRCLE;
69 while (x < 0) do70 x := x + FULL_CIRCLE;
71 Result := CosResults[x * MULTIPLIER];
72 end;
73 74 function MyCos(x: real): real; overload;
75 begin76 while (x > FULL_CIRCLE) do77 x := x - FULL_CIRCLE;
78 while (x < 0) do79 x := x + FULL_CIRCLE;
80 Result := CosResults[round(x * MULTIPLIER)];
81 end;
82 83 { ===================================================== }84 { ===================================================== }85 initialization86 begin87 InitArcAnswers;
88 end;
89 90 end.
Component Download:
http://www.delphi3000.com/article/3649/3649.zip