logN
Jump to navigation
Jump to search
The logarithm function performs a mathematical operation that is opposite of an exponential function (raising a base constant to a power). The logarithm of a number x in base base is any number n such that x = basen. This function takes and returns fixed-point numbers.
This was adapted from the Python code on Literate Programs.
#define MATH_E 178145
function int logN (int x, int base)
{
if (!base) base = MATH_E;
int integer = 0;
if (x < 1.0 && base < 1.0) return 0;
while (x < 1)
{
integer -= 1;
x = FixedMul (x, base);
}
while (x >= base)
{
integer += 1;
x = FixedDiv (x, base);
}
int partial = 0.5;
x = FixedMul (x, x);
int decimal = 0;
while (partial > 1) // Actually 0.0000152587890625
{
if (x >= base)
{
decimal += partial;
x = FixedDiv (x, base);
}
partial = FixedMul (partial, 0.5);
x = FixedMul (x, x);
}
return ((integer << 16) + decimal);
}