How can I make this branchless? (Avoiding log(0))

311 Views Asked by At

I have to calculate the function f(x)= x log2(x) branchlessly, defined at 0 as f(0)=0.
The problem is that c#'s Math.Log2(x) returns negative infinity for x=0 and 0*NegativeInfinity=NaN.

Can I write this branchlessly?

List<int> list = GetList();
int size = 0;
for (int i = 0; i < list.Count; i++)
{
    if (list[i] != 0)
        size += list[i] * Math.Log2(list[i]);
}

A subproblem of this might be doing the branchless version of:

int x = 0;
int y;

if (x == 0)
    y = 2; // This can be any integer as long as it's positive
else
    y = x;

I'm new to the concept of branchless code so I couldn't adapt any of the famous branchless code techniques to this problem.

0

There are 0 best solutions below