Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any fast way to check if two doubles has the same sign?

Any fast way to check if two doubles have the same sign? Assume the two doubles cannot be 0.

like image 589
user1899020 Avatar asked Dec 21 '25 19:12

user1899020


1 Answers

Potential solutions:

  1. a*b > 0: One floating-point multiply and one comparison.
  2. (a>0) == (b>0): Three comparisons.
  3. 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):

  1. a*b > 0: 0.42 ± 0.02s
  2. (a>0) == (b>0): 0.49 ± 0.01s
  3. Math.Sign(a) == Math.Sign(b): 1.11 ± 0.9s

Important 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);
}
like image 71
Kittsil Avatar answered Dec 24 '25 07:12

Kittsil