2007. augusztus 15., szerda
Fast sine and cosine calculations
Problem/Question/Abstract:
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.
unit sin_Tool;
interface
const
FULL_CIRCLE = 360;
HALF_CIRCLE = 180;
// TEN_CIRCLES = 3600;
function MySin(x: integer): real; overload;
function MySin(x: real): real; overload; // allow both reals or integers
function MyCos(x: integer): real; overload;
function MyCos(x: real): real; overload; // allow both reals or integers
{ ===================================================== }
{ ===================================================== }
implementation
uses
Math;
const
MULTIPLIER = 10;
NUM_ELEMENTS = FULL_CIRCLE * MULTIPLIER;
type
tArcAnswers = array[0..NUM_ELEMENTS] of real;
var
SinResults,
CosResults: tArcAnswers;
{ =====================================================
function DegToRad(x:real):real; // OK... no need .. its in the math unit...
===================================================== }
procedure InitArcAnswers;
var
c: integer;
begin
for c := 0 to NUM_ELEMENTS do
begin
SinResults[c] := sin(DegToRad(c / MULTIPLIER));
CosResults[c] := cos(DegToRad(c / MULTIPLIER));
end;
c := 1;
end;
{ ===================================================== }
function MySin(x: integer): real; overload;
begin
while (x > FULL_CIRCLE) do
x := x - FULL_CIRCLE;
while (x < 0) do
x := x + FULL_CIRCLE;
Result := SinResults[x * MULTIPLIER];
end;
function MySin(x: real): real; overload;
begin
while (x > FULL_CIRCLE) do
x := x - FULL_CIRCLE;
while (x < 0) do
x := x + FULL_CIRCLE;
Result := SinResults[round(x * MULTIPLIER)];
end;
{ ===================================================== }
function MyCos(x: integer): real; overload;
begin
while (x > FULL_CIRCLE) do
x := x - FULL_CIRCLE;
while (x < 0) do
x := x + FULL_CIRCLE;
Result := CosResults[x * MULTIPLIER];
end;
function MyCos(x: real): real; overload;
begin
while (x > FULL_CIRCLE) do
x := x - FULL_CIRCLE;
while (x < 0) do
x := x + FULL_CIRCLE;
Result := CosResults[round(x * MULTIPLIER)];
end;
{ ===================================================== }
{ ===================================================== }
initialization
begin
InitArcAnswers;
end;
end.
Component Download: 3649.zip
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése