/*-----------------------------------------------------------------------------

Copyright (C) 2016

A. Ronald Gallant
Post Office Box 659
Chapel Hill NC 27514-0659
USA

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

-------------------------------------------------------------------------------

Function      rationalbasetwo - approximate x with a rational base 2 number

Syntax        #include "sclfuncs.h"
              REAL rationalbasetwo(REAL x)

Prototype in  sclfuncs.h

Description   x is any REAL on entry, positive or negative. The return
              value has the same sign as x. Rounding is away from zero.
	      
Return value  The return value is as follows:
	      (a) 0 if x == 0
	      (b) 1/2^n    if 1/2^(n+1) < x <= 1/2^n
	      (c) 2^(n+1)  if       2^n < x <= 2^(n+1)
	      (d) -1/2^n   if   -1/2^n <= x < -1/2^(n+1)
	      (e) -2^(n+1) if -2^(n+1) <= x < -2^n
	      
Functions     Library: (none)
called        libscl:  (none)

------------------------------------------------------------------------------*/

#include "sclfuncs.h"

namespace scl {

  REAL rationalbasetwo(REAL x)
  {
    if (x == 0.0) return 0.0;
    REAL sign = x < 0 ? -1.0 : 1.0;
    x *= sign;
    REAL rv = 1.0;
    if (x < 1.0) {
      while (x < 1.0) {
        x *= 2.0;
        rv /= 2.0;
      }
    }
    while (x > 1.0) {
      x /= 2.0;
      rv *= 2.0;
    }
    rv *= sign;
    return rv;
  }

}
