Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

nan

(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++?

like image 791
user541686 Avatar asked Dec 27 '13 12:12

user541686


1 Answers

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.

like image 149
Yakk - Adam Nevraumont Avatar answered Dec 15 '22 00:12

Yakk - Adam Nevraumont