I need to implement some math functions without depending on a C library (such as exp, pow and log).. Where can I find algorithms or even code?
I need to implement some math functions without depending on a C library (such as exp, pow and log).. Where can I find algorithms or even code?
As long as you know how to perform these calculations without a calculator (can you believe a lot of us had to do this stuff by hand?!) then you should be able to figure it out pretty easily. I'll just give you one to get you started:
It doesn't handle negative exponents correctly, but you get the idea.Code:#include <stdio.h> double mypow(double x, double y) { double rv = 1.; while(y-- > 0) rv *= x; return rv; } int main(void) { int x = 2, y = 4; printf("%d\n", (int)mypow(x, y)); return 0; }
works fine for ints, but how about floating point? And how do you do logarithms by hand? (I only know to use log tables)
Last edited by ZeroG; 08-04-2004 at 12:06 AM.
You can do many things using series approximations. e.g.
clearly there's a bit of work to be done getting everything into the right formCode:ln((1+x)/(1-x)) = 2x + (2/3)x^3 + (2/5)x^5 + (2/7)x^7 + ... for |x| < 1
and working out how many terms to calculate but its not too hard.
Powers can be calculated using logs. eg:
for more series take a look at http://mathworld.wolfram.com/MaclaurinSeries.htmlCode:x^y = e^(y ln(x)) e^x = 1 + x + (1/2)x^2 + (1/3!)x^3 + (1/4!)x^4 + ...
Note: there may be quicker formulations that you can use, but I would get it working
first and understand the theory behind it. You can worry about speed-ups later!
DavT
-----------------------------------------------
thanks.
You can also look at the source for libm to see how they do it. As long as you give proper credit in your functions you can use their code.
..or you can use FPU trough inline assembly. Here's tutorial: http://masmforum.com/website/tutoria...ute/index.html (some asm knowledge required)
thanks all for links and ideas.