User talk:Creature/Logarithms

From OSDev Wiki
Jump to: navigation, search

This is both mathematically exact and precise, and does not require a power() or similar function. It suffers from one problem: the second part is totally nonobvious for the non-math-geeks. Formula grabbed from Wikipedia. Use as you please - Combuster 22:15, 16 February 2010 (UTC)

#define EULER 2.718281828459045235360287L
double log(double x)
{
    if (!(x > 0)) return -INFINITY; // handles NaN and invalid inputs
 
    // compute integer part of answer
    double base = 0;
    //normalize to near-1 (0.6-1.7)
    while (x < 0.6)
    {
        x *= EULER;
        base--;
    }
    while (x > 1.7)
    {
        x /= EULER;
        base++;
    }
 
    // expand the taylor-maclaurin series for ln
    double y = (x-1.0)/(x+1.0);
    double fraction = 0.0;
    double bottomroot = 1.0;
    double power = 1.0;
    int lpc = 0;
 
    while (lpc < expansions)
    {
        fraction += power / bottomroot;
        power *= y * y;
        bottomroot += 2.0;
        lpc++; 
    }
    fraction *= 2.0 * y;
 
    return(base + fraction);
}
  • Thanks for the suggestion (I moved your comment here so I could reply to it without crowding my own article and it seems kind of ungrateful to just remove the comment ;). I've put the link to Wikipedia and a note about the alternative way inside the article (I also gave you credit for the suggestion). In fact, I was studying maths yesterday, when I suddenly found this way. Since I'm only just a student, I don't know a great amount of maths (just mostly the 'basic' stuff). I've actually never studied the Taylor series before, but I have taken a look at them myself and have an idea what they are for and how they work. --Creature 11:15, 17 February 2010 (UTC)
Personal tools
Namespaces
Variants
Actions
Navigation
About
Toolbox