Inspired by TCA's posts here and on the WIP board a little Fixed Point library (using 4 byte Integers, so it's DBC compatible). It contains conversion from floating point to fixed point and back, basic arithmetics (add, sub, mul, div) as well as cos and sin functions. The demo plots a sine and cosine wave.
Where and when to use it? I don't know.
rem Globals
Dim PI(0)
Dim PI_OVER_2(0)
PI(0) = 205887
PI_OVER_2(0) = PI(0) / 2
rem Test plot ----------------------------------------------------
pi# = 3.14159265359
for x = 0 to 360
rad# = x * pi# / 180
fpRad = float2FP(rad#)
mysin# = FP2Float(fp_Sin(fpRad))
mycos# = FP2Float(fp_Cos(fpRad))
ink rgb(255,0,0),0
dot x,(mysin# * 100) + 200
ink rgb(0,0,255),0
dot x,(mycos# * 100) + 200
next i
wait key
end
rem Test plot end -------------------------------------------------
function Float2FP(value#)
result = value# * 65536
endfunction result
function fp2Float(value)
result# = value / 65536.0
endfunction result#
function fp_Add(Value1, Value2)
endfunction Value1+Value2
function fp_Sub(Value1, Value2)
endfunction Value1-Value2
function fp_Mul(Value1, Value2)
if abs(value1) > abs(value2)
result = value1 / 256 * value2 / 256
else
result = value2 / 256 * value1 / 256
endif
endfunction result
function fp_Div(Value1, Value2)
result = (value1 * 256) / (Value2 / 256)
endfunction result
function fp_Sqrt(Value)
result = (Value + 65536) / 2
for i = 0 to 7
result = (result + fp_Div(Value,result)) / 2
next i
endfunction result
function fp_Sin(Value)
rem Ported from the Java IAppli Fixed Point Math Library
rem http://www.ai.mit.edu/people/hqm/imode/fplib
SK1 = 498
SK2 = 10882
sign = 1
if (Value > PI_OVER_2(0)) and (value <= PI(0)) then Value = PI(0) - Value
if (Value > PI(0)) and (Value <= (PI(0) + PI_OVER_2(0)))
Value = Value - PI(0)
sign = -1
endif
if (Value > (PI(0) + PI_OVER_2(0)))
Value = (PI(0) * 2) - Value
sign = -1
endif
sqr = fp_Mul(Value,Value)
result = SK1
result = fp_MUL(result,sqr)
result = result - SK2
result = fp_Mul(result,sqr)
result = result + 65536
result = fp_Mul(result, value)
result = sign * result
endfunction result
function fp_Cos(Value)
rem Ported from the Java IAppli Fixed Point Math Library
rem http://www.ai.mit.edu/people/hqm/imode/fplib
CK1 = 2328
CK2 = 32551
sign = 1
if (Value > PI_OVER_2(0)) and (Value <= PI(0))
value = PI(0) - value
sign = -1
else
if (Value > PI_OVER_2(0)) and (Value <= (PI(0) + PI_OVER_2(0)))
value = value - PI(0)
sign = -1
endif
endif
if Value > (PI(0) + PI_OVER_2(0)) then value = (PI(0)*2)-value
sqr = fp_Mul(Value,Value)
result = CK1
result = fp_MUL(result,sqr)
result = result - CK2
result = fp_Mul(result,sqr)
result = result + 65536
result = result * sign
endfunction result
Me, I'll sit and write this love song as I all too seldom do
build a little fire this midnight. It's good to be back home with you.