Stand-alone C# code for log(1+x)

See the C++ version of this page for documentation.

using System;

// compute log(1+x) without losing precision for small values of x
static double LogOnePlusX(double x)
{
    if (x <= -1.0)
    {
        string msg = String.Format("Invalid input argument: {0}", x);
        throw new ArgumentOutOfRangeException(msg);
    }

    if (Math.Abs(x) > 1e-4)
    {
        // x is large enough that the obvious evaluation is OK
        return Math.Log(1.0 + x);
    }

    // Use Taylor approx. log(1 + x) = x - x^2/2 with error roughly x^3/3
    // Since |x| < 10^-4, |x|^3 < 10^-12, relative error less than 10^-8

    return (-0.5*x + 1.0)*x;
}

This code is in the public domain. Do whatever you want to with it, no strings attached.

Other versions: C++, Python

More stand-alone numerical code