Math Calculation
Charles Law
Posts: 72
Does anyone has idea on how to calculate log number in AMX program? I think we don't have any log function to do this.
Thanks
Charles
Thanks
Charles
0
Comments
Another answer could be: Check the Java language in DUET. I would imagine that JAVA has a LOG and a LN function built in.
Jeff
if y = a^x
then x = loga*y (log y to the base of a)
so you would have to do it something like long division
I'll have a crack at it tonight.
You can calculate the natural log from a lookup table of powers of e and the fact that:
ln(x+1) = x - x^2/2 + x^3/3 -x^4/4 . . .
I've created such a function that seems to work decently with a 16 bit integer input. The function could be modifed to work with a float input but the lookup table would need to be expanded to about 90 elements to accomodate values up to E39.
Once the natural log is calculated, it can be converted to any base using the relationship:
logb(x) = ln(x)/ln(b)
for common logs:
log(x) = ln(x)/ln(10) = ln(x)/2.302585
for base 2 logs:
log2(x) = ln(x)/ ln(2) = ln(x)/.693147
So log10(100) = 2
NatLog(100)/NatLog(10) = 2
I gave up when I needed an exponential function that could raise a number to the power of a float. It's easy to raise a number to the power of an integer, but not a float.
I didn't do that; I looked it up:
a^x = 1+ x*ln(a) + (x*ln(a))^2/2! + (x*ln(a))^3/3! + ...
Thinking about these questions has made me wonder how calulators and computer functions actually do calculations involving logarithms. I don't know the answer to that question and a brief excursion down the information super-highway didn't reveal it. There must be some trick of which I am unaware.
Harold
I did this, it works quite well
DEFINE_FUNCTION float log (float base,float value)
{
local_var float epsilon
local_var sinteger integer_value
local_var float decfrac
local_var float partial
//This Log routine is accurate to 4 places
//
//Found at http://www.answers.com/topic/logarithm
//Converted to AMX by William Holt, Intelligent Homes (In Control) Ltd.
//
//Usually base is e
//e is approx 2.718282
//but for use with linear volume to db conversion, base is 10
if (value <> 0)
{
epsilon = 0.000000000001
integer_value = 0
While (value < 1)
{
integer_value = integer_value - 1
value = value * base
}
While (value >= base)
{
integer_value = integer_value + 1
value = value / base
}
decfrac = 0
partial = 0.5
value = value * value
While (partial > epsilon)
{
While (value >= base)
{
decfrac = decfrac + partial
value = value / base
}
partial = partial / 2
value = value * value
}
decfrac = decfrac + integer_value
RETURN decfrac
}
else
{
RETURN 0
}
}
Can anyone post a function to do x^y or powf(x,y) or an exp function? please.