This question I have didn't fully help me, although it gave me a few details.
My current based code:
#define e 2.7182818284590452353602874713527
double logarithm(long double dec) {
// return log10f(dec);
return result;
}
What I learned from the linked question:
^
is not for exponents (and I'm planning on making this syntax an exponential form, which might mean abandoning the power()
function), rather it's an XOR operator.log10f
source code, but it's kinda confusing, so not worth it for me.Now the criteria I have for this function is that it is made from scratch, no multiple functions, and make it a simple sort (even though I doubt that logarithm isn't even simple).
The answer's code:
#include <math.h>
float log_num(int num) {
return log10f(num);
}
Yes, fairly simple, but as a challenge, I want to not use the log()
functions themselves though I'm still relying on <math.h>
's functions.
Question: What's a simple form of making a logarithm function in scratch without the built-in logarithm functions? If without using <math.h>
, then how is that?
If you need something reasonably accurate, you could use the Taylor series formula. Increase the number of iterations if you need better precision.
#define EULER_CONST 2.718281828459045235
#define TAYLOR_ITERATIONS 20
double nat_log(double x) {
// Trap illegal values
if (x <= 0) {
return 0.0/0.0; // NaN
}
// Confine x to a sensible range
int power_adjust = 0;
while (x > 1.0) {
x /= EULER_CONST;
power_adjust++;
}
while (x < .25) {
x *= EULER_CONST;
power_adjust--;
}
// Now use the Taylor series to calculate the logarithm
x -= 1.0;
double t = 0.0, s = 1.0, z = x;
for (int k=1; k<=TAYLOR_ITERATIONS; k++) {
t += z * s / k;
z *= x;
s = -s;
}
// Combine the result with the power_adjust value and return
return t + power_adjust;
}