...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
#include <boost/math/special_functions/sign.hpp>
namespace boost{ namespace math{ template<class T> int signbit(T x); template <class T> inline int sign (const T& z); template <class T> inline T copysign (const T& x, const T& y); template <class T> inline T changesign (const T& z); }} // namespaces
template<class T> int signbit(T x);
Returns a non-zero value if the sign bit is set in variable x,
otherwise 0
.
Important | |
---|---|
The return value from this function is zero or not-zero and not zero or one. |
template <class T> inline int sign (const T& z);
Returns 1
if x
> 0
,
-1
if x < 0
, and 0
if x is zero.
template <class T> inline T copysign (const T& x, const T& y);
Sets the sign of x to be the same as the sign of y.
See C99 7.12.11.1 The copysign functions for more detail.
template <class T> inline T changesign (const T& z);
Returns a floating point number with a binary representation where the signbit is the opposite of the sign bit in x, and where the other bits are the same as in x.
This function is widely available, but not specified in any standards.
Rationale: Not specified by TR1, but changesign(x)
is both easier to read and more efficient than
copysign(x, signbit(x) ? 1.0 : -1.0);
For finite values, this function has the same effect as simple negation,
the assignment z = -z, but for nonfinite values, infinities
and NaNs, the changesign(x)
function
may be the only portable way to ensure that the sign bit is changed.
One of the bits in the binary representation of a floating-point number gives the sign, and the remaining bits give the absolute value. That bit is known as the sign bit. The sign bit is set = 1 for negative numbers, and is not set = 0 for positive numbers. (This is true for all binary representations of floating point numbers that are used by modern microprocessors.)
C++
TR1 specifies copysign
functions and function templates for accessing the sign bit.
For user-defined types (UDT), the sign may be stored in some other way. They may also not provide infinity or NaNs. To use these functions with a UDT, it may be necessary to explicitly specialize then for UDT type T.
signbit(3.5) is zero (or false) signbit(-7.1) is 1 (or true) copysign(4.2, 7.9) is 4.2 copysign(3.5 -1.4) is -3.5 copysign(-4.2, 1.0) is 4.2 copysign(-8.6, -3.3) is -8.6 changesign(6.9) is -6.9 changesign(-1.8) is 1.8
The library supports the following binary floating-point formats:
The library does not support the VAX floating-point formats. (These are available on VMS, but the default on VMS is the IEEE 754 floating-point format.)
The main portability issues are:
#if defined(__ia64) || defined(__ia64__)
|| defined(_M_IA64)
is used to determine the processor type.
The library has passed all tests on the following platforms: