function bd0 = binodeviance_scalar(x,np)
%BINODEVIANCE Deviance term for a single element of binomial and Poisson probability
%calculation. All inputs must be scalar.

%   Copyright 2019 The MathWorks, Inc.

if abs(x-np) < 0.1*(x+np)
    % If "x/np" is close to 1:
    s = (x-np)*(x-np)/(x+np);
    v = (x-np)/(x+np);
    ej = 2*x*v;
    ok = true;
    j = 0;
    while ok
        ej = ej*v*v;
        j = j+1;
        s1 = s + ej/(2*j+1);
        ok = ok && s1~=s;
        s = s1;
    end
    bd0 = s;
else
    % If "x/np" is not close to 1:
    bd0 = x*log(x/np)+np-x;
end

end
