Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define condition for square root

This macro is for computing sqrt(x),

#define SQRT(x)     ((x)<=0.0||(x)!=(x)?0.0:sqrt(x))

I can't understand in which case the second condition (x)!=(x) may be true?

like image 867
Hadi Karimi Avatar asked Nov 29 '25 11:11

Hadi Karimi


1 Answers

(x) != (x) will be true if x is a IEEE 754 Not-a-number (NaN). I.e. this macro tries to coerce the result to 0.0 for arguments values for which square root is not defined. The sqrt(3) Linux man page summarizes the return values nicely:

RETURN VALUE

On success, these functions return the square root of x.

  • If x is a NaN, a NaN is returned.

  • If x is +0 (-0), +0 (-0) is returned.

  • If x is positive infinity, positive infinity is returned.

  • If x is less than -0, a domain error occurs, and a NaN is returned.

Therefore this expression makes sure that instead of NaN, 0 would be returned for the 1st and the 4th cases, and additionally, errno be untouched and that no floating point exception would occur.


(BTW this weird macro is not safe to use if you have side effects in the macro argument, so it'd better be replaced by an inline function or similar)