Return Positive value of a number - page 3

 

Ok, so I've added the latest proposals to the list:

class CStopwatch
  {
protected:
   ulong             m_ticks;
public:
   void              Start() { m_ticks=GetMicrosecondCount(); }
   void              Stop() { m_ticks=GetMicrosecondCount()-m_ticks; }
   ulong             Ticks() { return m_ticks; }
  };

union UDouble
  {
   double d;
   uchar c[8];
  };

int OnInit()
  {
   CStopwatch watch;
   UDouble numu;
   
   watch.Start();
   for(int i=-10000000; i<10000000; i++)
     {
      double num=i*0.1;
      //numu.d=i*0.1;
      
      //num = MathSqrt(MathPow(num,2)); // 1800000
      //num *= ((int)(num-1)|1) % 2; // 461000
      //num = num*(-1 + (2 * (num > 0))); // 386000
      //num = num*(num>=0) -num*(num<0); // 263000
      //num = MathSqrt(num*num); // 239000
      //num = (num<0 ? -num : num); // 146000
      //num = (num < NULL) ? num * -1 : num; // 146000
      //num = num * ((num < NULL) ? -1 : 1); // 100000
      //if(num<0) num=num*-1; // 90000
      //if(num<0) num=-num; // 90000
      //num = MathAbs(num); // 60000
      //num = -num; // 60000
      //int n = ~i + 1; // 83000
      //int n = i & ((i < NULL) ? 0x7fffffff : 0xffffffff); // 70000
      //int n = (i << 1) >> 1; // 67000
      //int n = i & 0x7fffffff; // 60000
      /*nop*/; // 60000
      //numu.c[7] &= 127; // 60000
     }
   watch.Stop();
   Print("ticks: ",watch.Ticks());

The solutions in green are proven to work on any double (save the fact that squaring may cause an overflow). The other solutions are just there to get an impression of the performance or don't work with all numbers.

The fastest solution is either MathAbs() or &127 (clearing the sign) via union.

Reason: