How to portably force NAN * zero give zero in a particular expression without branching?

StackOverflow https://stackoverflow.com/questions/20800371

  •  21-09-2022
  •  | 
  •  

Question

(I feel like this should be a duplicate question, but I couldn't find the right search terms when searching.)

In general, (quiet) NAN times zero should give NAN -- and it does.

However, in one particular performance-critical part of my code, I want zero times anything to be zero.

What's a fast way to do this in C++?

Was it helpful?

Solution

double mymult(double a, double b){
  double result[]={a*b,0.};
  return result[(a==0.)|(b==0.)];
}

should avoid branches: double check the generated assembly.

Not all bool calculations imply a branch.

OTHER TIPS

You cannot do it with arithmetic. You have to test for zero.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top