A function to calculate the product logarithm function, also known as the Lambert W function.
Use it via
double lam = LambertW(1);
public static double LambertW(double x)
{
// LambertW is not defined in this section
if (x < -Math.Exp(-1))
throw new Exception("The LambertW-function is not defined for " + x + ".");
// computes the first branch for real values only
// amount of iterations (empirically found)
int amountOfIterations = Math.Max(4, (int)Math.Ceiling(Math.Log10(x) / 3));
// initial guess is based on 0 < ln(a) < 3
double w = 3 * Math.Log(x + 1) / 4;
// Halley's method via eqn (5.9) in Corless et al (1996)
for (int i = 0; i < amountOfIterations; i++)
w = w - (w * Math.Exp(w) - x) / (Math.Exp(w) * (w + 1) - (w + 2) * (w * Math.Exp(w) - x) / (2 * w + 2));
return w;
}
The metanumerics .net library on Github implements this and many more functions which may be useful.
e.g. in documentation