function w = BrandW(x)
% Matt Brand's recurrence for computing LambertW(-1,-exp(-x))
% w = BrandW(x)
%
% Follows the method described in:
% Matthew Brand: Structure Learning in Conditional Probability 
% Models via an Entropic Prior and Parameter Extinction. 
% Neural Computation 11(5): 1155-1182 (1999)

% Author: David Ross, 2003.

iters = 0;
max_iters = 1000000;

w_old = -x+1; % just make sure that initially (w_old ~= w)
w = -x;

% iterate until we've converged to machine precision,
% or max_iters iterations (whichever comes first)
while w_old ~= w
    w_old = w;
    w = -x - log(abs(w_old));
    iters = iters + 1;
    if iters == max_iters
        warning('maximum number of iterations reached');
        break;
    end
end
