Any fast way to check if two doubles have the same sign? Assume the two doubles cannot be 0.
Potential solutions:
a*b > 0: One floating-point multiply and one comparison.(a>0) == (b>0): Three comparisons.Math.Sign(a) == Math.Sign(b): Two function calls and one comparison.Speed comparison:
It's about what you'd expect (see experimental setup at the bottom):
a*b > 0: 0.42 ± 0.02s(a>0) == (b>0): 0.49 ± 0.01sMath.Sign(a) == Math.Sign(b): 1.11 ± 0.9sImportant notes:
As noted by greybeard in the comments, method 1 is susceptible to problems if the values multiply to something smaller than Double.Epsilon. Unless you can guarantee that the multiple is always larger than this, you should probably go with method 2.
Experimental setup:
The following code was run 16 times on http://rextester.com/.
public static void Main(string[] args)
{
double a = 1e-273;
double b = a;
bool equiv = false;
for(int i=0; i<100000000; ++i) {
equiv = THE_COMPARISON;
b += a;
}
//Your code goes here
Console.WriteLine(equiv);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With