| 1 | // Copyright 2009 Google Inc. All Rights Reserved. |
| 2 | // |
| 3 | // ExactFloat is a multiple-precision floating point type based on the OpenSSL |
| 4 | // Bignum library. It has the same interface as the built-in "float" and |
| 5 | // "double" types, but only supports the subset of operators and intrinsics |
| 6 | // where it is possible to compute the result exactly. So for example, |
| 7 | // ExactFloat supports addition and multiplication but not division (since in |
| 8 | // general, the quotient of two floating-point numbers cannot be represented |
| 9 | // exactly). Exact arithmetic is useful for geometric algorithms, especially |
| 10 | // for disambiguating cases where ordinary double-precision arithmetic yields |
| 11 | // an uncertain result. |
| 12 | // |
| 13 | // ExactFloat is a subset of the faster and more capable MPFloat class (which |
| 14 | // is based on the GNU MPFR library). The main reason to use this class |
| 15 | // rather than MPFloat is that it is subject to a BSD-style license rather |
| 16 | // than the much restrictive LGPL license. |
| 17 | // |
| 18 | // It has the following features: |
| 19 | // |
| 20 | // - ExactFloat uses the same syntax as the built-in "float" and "double" |
| 21 | // types, for example: x += 4 + fabs(2*y*y - z*z). There are a few |
| 22 | // differences (see below), but the syntax is compatible enough so that |
| 23 | // ExactFloat can be used as a template argument to templatized classes |
| 24 | // such as Vector2, VectorN, Matrix3x3, etc. |
| 25 | // |
| 26 | // - Results are not rounded; instead, precision is increased so that the |
| 27 | // result can be represented exactly. An inexact result is returned only |
| 28 | // in the case of underflow or overflow (yielding signed zero or infinity |
| 29 | // respectively), or if the maximum allowed precision is exceeded (yielding |
| 30 | // NaN). ExactFloat uses IEEE 754-2008 rules for handling infinities, NaN, |
| 31 | // rounding to integers, etc. |
| 32 | // |
| 33 | // - ExactFloat only supports calculations where the result can be |
| 34 | // represented exactly. Therefore it supports intrinsics such as fabs() |
| 35 | // but not transcendentals such as sin(), sqrt(), etc. |
| 36 | // |
| 37 | // Syntax Compatibility with "float" and "double" |
| 38 | // ---------------------------------------------- |
| 39 | // |
| 40 | // ExactFloat supports a subset of the operators and intrinsics for the |
| 41 | // built-in "double" type. (Thus it supports fabs() but not fabsf(), for |
| 42 | // example.) The syntax is different only in the following cases: |
| 43 | // |
| 44 | // - Casts and implicit conversions to built-in types (including "bool") are |
| 45 | // not supported. So for example, the following will not compile: |
| 46 | // |
| 47 | // ExactFloat x = 7.5; |
| 48 | // double y = x; // ERROR: use x.ToDouble() instead |
| 49 | // long z = x; // ERROR: use x.ToDouble() or lround(trunc(x)) |
| 50 | // q = static_cast<int>(x); // ERROR: use x.ToDouble() or lround(trunc(x)) |
| 51 | // if (x) { ... } // ERROR: use (x != 0) instead |
| 52 | // |
| 53 | // - The glibc floating-point classification macros (fpclassify, isfinite, |
| 54 | // isnormal, isnan, isinf) are not supported. Instead there are |
| 55 | // zero-argument methods: |
| 56 | // |
| 57 | // ExactFloat x; |
| 58 | // if (isnan(x)) { ... } // ERROR: use (x.is_nan()) instead |
| 59 | // if (isinf(x)) { ... } // ERROR: use (x.is_inf()) instead |
| 60 | // |
| 61 | // Using ExactFloat with Vector3, etc. |
| 62 | // ----------------------------------- |
| 63 | // |
| 64 | // ExactFloat can be used with templatized classes such as Vector2 and Vector3 |
| 65 | // (see "util/math/vector3-inl.h"), with the following limitations: |
| 66 | // |
| 67 | // - Cast() can be used to convert other vector types to an ExactFloat vector |
| 68 | // type, but not the other way around. This is because there are no |
| 69 | // implicit conversions from ExactFloat to built-in types. You can work |
| 70 | // around this by calling an explicit conversion method such as |
| 71 | // ToDouble(). For example: |
| 72 | // |
| 73 | // typedef Vector3<ExactFloat> Vector3_xf; |
| 74 | // Vector3_xf x; |
| 75 | // Vector3_d y; |
| 76 | // x = Vector3_xf::Cast(y); // This works. |
| 77 | // y = Vector3_d::Cast(x); // This doesn't. |
| 78 | // y = Vector3_d(x[0].ToDouble(), x[1].ToDouble(), x[2].ToDouble()); // OK |
| 79 | // |
| 80 | // - IsNaN() is not supported because it calls isnan(), which is defined as a |
| 81 | // macro in <math.h> and therefore can't easily be overrided. |
| 82 | // |
| 83 | // Precision Semantics |
| 84 | // ------------------- |
| 85 | // |
| 86 | // Unlike MPFloat, ExactFloat does not allow a maximum precision to be |
| 87 | // specified (it is always unbounded). Therefore it does not have any of the |
| 88 | // corresponding constructors. |
| 89 | // |
| 90 | // The current precision of an ExactFloat (i.e., the number of bits in its |
| 91 | // mantissa) is returned by prec(). The precision is increased as necessary |
| 92 | // so that the result of every operation can be represented exactly. |
| 93 | |
| 94 | #ifndef UTIL_MATH_EXACTFLOAT_EXACTFLOAT_H_ |
| 95 | #define UTIL_MATH_EXACTFLOAT_EXACTFLOAT_H_ |
| 96 | |
| 97 | #include <math.h> |
| 98 | #include <limits.h> |
| 99 | #include <iostream> |
| 100 | using std::ostream; |
| 101 | using std::cout; |
| 102 | using std::endl; |
| 103 | |
| 104 | #include <string> |
| 105 | using std::string; |
| 106 | |
| 107 | #include "base/logging.h" |
| 108 | #include "base/integral_types.h" |
| 109 | |
| 110 | namespace bn { |
| 111 | #include "bn/bn.h" |
| 112 | } |
| 113 | |
| 114 | using namespace bn; |
| 115 | |
| 116 | class ExactFloat { |
| 117 | public: |
| 118 | // The following limits are imposed by OpenSSL. |
| 119 | |
| 120 | // The maximum exponent supported. If a value has an exponent larger than |
| 121 | // this, it is replaced by infinity (with the appropriate sign). |
| 122 | static const int kMaxExp = 200*1000*1000; // About 10**(60 million) |
| 123 | |
| 124 | // The minimum exponent supported. If a value has an exponent less than |
| 125 | // this, it is replaced by zero (with the appropriate sign). |
| 126 | static const int kMinExp = -kMaxExp; // About 10**(-60 million) |
| 127 | |
| 128 | // The maximum number of mantissa bits supported. If a value has more |
| 129 | // mantissa bits than this, it is replaced with NaN. (It is expected that |
| 130 | // users of this class will never want this much precision.) |
| 131 | static const int kMaxPrec = 64 << 20; // About 20 million digits |
| 132 | |
| 133 | // Rounding modes. kRoundTiesToEven and kRoundTiesAwayFromZero both round |
| 134 | // to the nearest representable value unless two values are equally close. |
| 135 | // In that case kRoundTiesToEven rounds to the nearest even value, while |
| 136 | // kRoundTiesAwayFromZero always rounds away from zero. |
| 137 | enum RoundingMode { |
| 138 | kRoundTiesToEven, |
| 139 | kRoundTiesAwayFromZero, |
| 140 | kRoundTowardZero, |
| 141 | kRoundAwayFromZero, |
| 142 | kRoundTowardPositive, |
| 143 | kRoundTowardNegative |
| 144 | }; |
| 145 | |
| 146 | ///////////////////////////////////////////////////////////////////////////// |
| 147 | // Constructors |
| 148 | |
| 149 | // The default constructor initializes the value to zero. (The initial |
| 150 | // value must be zero rather than NaN for compatibility with the built-in |
| 151 | // float types.) |
| 152 | inline ExactFloat(); |
| 153 | |
| 154 | // Construct an ExactFloat from a "double". The constructor is implicit so |
| 155 | // that this class can be used as a replacement for "float" or "double" in |
| 156 | // templatized libraries. (With an explicit constructor, code such as |
| 157 | // "ExactFloat f = 2.5;" would not compile.) All double-precision values are |
| 158 | // supported, including denormalized numbers, infinities, and NaNs. |
| 159 | ExactFloat(double v); |
| 160 | |
| 161 | // Construct an ExactFloat from an "int". Note that in general, ints are |
| 162 | // automatically converted to doubles and so would be handled by the |
| 163 | // constructor above. However, the particular argument (0) is ambiguous; the |
| 164 | // compiler doesn't know whether to treat it as a "double" or "NULL" |
| 165 | // (invoking the const char* constructor below). |
| 166 | // |
| 167 | // We do not provide constructors for "unsigned", "long", "unsigned long", |
| 168 | // "long long", or "unsigned long long", since these types are not typically |
| 169 | // used in floating-point calculations and it is safer to require them to be |
| 170 | // explicitly cast. |
| 171 | ExactFloat(int v); |
| 172 | |
| 173 | // Construct an ExactFloat from a string (such as "1.2e50"). Requires that |
| 174 | // the value is exactly representable as a floating-point number (so for |
| 175 | // example, "0.125" is allowed but "0.1" is not). |
| 176 | explicit ExactFloat(const char* s) { Unimplemented(); } |
| 177 | |
| 178 | // Copy constructor. |
| 179 | ExactFloat(const ExactFloat& b); |
| 180 | |
| 181 | // The destructor is not virtual for efficiency reasons. Therefore no |
| 182 | // subclass should declare additional fields that require destruction. |
| 183 | inline ~ExactFloat(); |
| 184 | |
| 185 | ///////////////////////////////////////////////////////////////////// |
| 186 | // Constants |
| 187 | // |
| 188 | // As an alternative to the constants below, you can also just use the |
| 189 | // constants defined in <math.h>, for example: |
| 190 | // |
| 191 | // ExactFloat x = NAN, y = -INFINITY; |
| 192 | |
| 193 | // Return an ExactFloat equal to positive zero (if sign >= 0) or |
| 194 | // negative zero (if sign < 0). |
| 195 | static ExactFloat SignedZero(int sign); |
| 196 | |
| 197 | // Return an ExactFloat equal to positive infinity (if sign >= 0) or |
| 198 | // negative infinity (if sign < 0). |
| 199 | static ExactFloat Infinity(int sign); |
| 200 | |
| 201 | // Return an ExactFloat that is NaN (Not-a-Number). |
| 202 | static ExactFloat NaN(); |
| 203 | |
| 204 | ///////////////////////////////////////////////////////////////////////////// |
| 205 | // Accessor Methods |
| 206 | |
| 207 | // Return the maximum precision of the ExactFloat. This method exists only |
| 208 | // for compatibility with MPFloat. |
| 209 | int max_prec() const { return kMaxPrec; } |
| 210 | |
| 211 | // Return the actual precision of this ExactFloat (the current number of |
| 212 | // bits in its mantissa). Returns 0 for non-normal numbers such as NaN. |
| 213 | int prec() const; |
| 214 | |
| 215 | // Return the exponent of this ExactFloat given that the mantissa is in the |
| 216 | // range [0.5, 1). It is an error to call this method if the value is zero, |
| 217 | // infinity, or NaN. |
| 218 | int exp() const; |
| 219 | |
| 220 | // Set the value of the ExactFloat to +0 (if sign >= 0) or -0 (if sign < 0). |
| 221 | void set_zero(int sign); |
| 222 | |
| 223 | // Set the value of the ExactFloat to positive infinity (if sign >= 0) or |
| 224 | // negative infinity (if sign < 0). |
| 225 | void set_inf(int sign); |
| 226 | |
| 227 | // Set the value of the ExactFloat to NaN (Not-a-Number). |
| 228 | void set_nan(); |
| 229 | |
| 230 | // Unfortunately, isinf(x), isnan(x), isnormal(x), and isfinite(x) are |
| 231 | // defined as macros in <math.h>. Therefore we can't easily extend them |
| 232 | // here. Instead we provide methods with underscores in their names that do |
| 233 | // the same thing: x.is_inf(), etc. |
| 234 | // |
| 235 | // These macros are not implemented: signbit(x), fpclassify(x). |
| 236 | |
| 237 | // Return true if this value is zero (including negative zero). |
| 238 | inline bool is_zero() const; |
| 239 | |
| 240 | // Return true if this value is infinity (positive or negative). |
| 241 | inline bool is_inf() const; |
| 242 | |
| 243 | // Return true if this value is NaN (Not-a-Number). |
| 244 | inline bool is_nan() const; |
| 245 | |
| 246 | // Return true if this value is a normal floating-point number. Non-normal |
| 247 | // values (zero, infinity, and NaN) often need to be handled separately |
| 248 | // because they are represented using special exponent values and their |
| 249 | // mantissa is not defined. |
| 250 | inline bool is_normal() const; |
| 251 | |
| 252 | // Return true if this value is a normal floating-point number or zero, |
| 253 | // i.e. it is not infinity or NaN. |
| 254 | inline bool is_finite() const; |
| 255 | |
| 256 | // Return true if the sign bit is set (this includes negative zero). |
| 257 | inline bool sign_bit() const; |
| 258 | |
| 259 | // Return +1 if this ExactFloat is positive, -1 if it is negative, and 0 |
| 260 | // if it is zero or NaN. Note that unlike sign_bit(), sgn() returns 0 for |
| 261 | // both positive and negative zero. |
| 262 | inline int sgn() const; |
| 263 | |
| 264 | ///////////////////////////////////////////////////////////////////////////// |
| 265 | // Conversion Methods |
| 266 | // |
| 267 | // Note that some conversions are defined as functions further below, |
| 268 | // e.g. to convert to an integer you can use lround(), llrint(), etc. |
| 269 | |
| 270 | // Round to double precision. Note that since doubles have a much smaller |
| 271 | // exponent range than ExactFloats, very small values may be rounded to |
| 272 | // (positive or negative) zero, and very large values may be rounded to |
| 273 | // infinity. |
| 274 | // |
| 275 | // It is very important to make this a named method rather than an implicit |
| 276 | // conversion, because otherwise there would be a silent loss of precision |
| 277 | // whenever some desired operator or function happens not to be implemented. |
| 278 | // For example, if fabs() were not implemented and "x" and "y" were |
| 279 | // ExactFloats, then x = fabs(y) would silently convert "y" to a "double", |
| 280 | // take its absolute value, and convert it back to an ExactFloat. |
| 281 | double ToDouble() const; |
| 282 | |
| 283 | // Return a human-readable string such that if two values with the same |
| 284 | // precision are different, then their string representations are different. |
| 285 | // The format is similar to printf("%g"), except that the number of |
| 286 | // significant digits depends on the precision (with a minimum of 10). |
| 287 | // Trailing zeros are stripped (just like "%g"). |
| 288 | // |
| 289 | // Note that if two values have different precisions, they may have the same |
| 290 | // ToString() value even though their values are slightly different. If you |
| 291 | // need to distinguish such values, use ToUniqueString() intead. |
| 292 | string ToString() const; |
| 293 | |
| 294 | // Return a string formatted according to printf("%Ng") where N is the given |
| 295 | // maximum number of significant digits. |
| 296 | string ToStringWithMaxDigits(int max_digits) const; |
| 297 | |
| 298 | // Return a human-readable string such that if two ExactFloats have different |
| 299 | // values, then their string representations are always different. This |
| 300 | // method is useful for debugging. The string has the form "value<prec>", |
| 301 | // where "prec" is the actual precision of the ExactFloat (e.g., "0.215<50>"). |
| 302 | string ToUniqueString() const; |
| 303 | |
| 304 | // Return an upper bound on the number of significant digits required to |
| 305 | // distinguish any two floating-point numbers with the given precision when |
| 306 | // they are formatted as decimal strings in exponential format. |
| 307 | static int NumSignificantDigitsForPrec(int prec); |
| 308 | |
| 309 | // Output the ExactFloat in human-readable format, e.g. for logging. |
| 310 | friend ostream& operator<<(ostream& o, ExactFloat const& f) { |
| 311 | return o << f.ToString(); |
| 312 | } |
| 313 | |
| 314 | ///////////////////////////////////////////////////////////////////////////// |
| 315 | // Other Methods |
| 316 | |
| 317 | // Round the ExactFloat so that its mantissa has at most "max_prec" bits |
| 318 | // using the given rounding mode. Requires "max_prec" to be at least 2 |
| 319 | // (since kRoundTiesToEven doesn't make sense with fewer bits than this). |
| 320 | ExactFloat RoundToMaxPrec(int max_prec, RoundingMode mode) const; |
| 321 | |
| 322 | ///////////////////////////////////////////////////////////////////////////// |
| 323 | // Operators |
| 324 | |
| 325 | // Assignment operator. |
| 326 | ExactFloat& operator=(const ExactFloat& b); |
| 327 | |
| 328 | // Unary plus. |
| 329 | ExactFloat operator+() const { return *this; } |
| 330 | |
| 331 | // Unary minus. |
| 332 | ExactFloat operator-() const; |
| 333 | |
| 334 | // Addition. |
| 335 | friend ExactFloat operator+(const ExactFloat& a, const ExactFloat& b); |
| 336 | |
| 337 | // Subtraction. |
| 338 | friend ExactFloat operator-(const ExactFloat& a, const ExactFloat& b); |
| 339 | |
| 340 | // Multiplication. |
| 341 | friend ExactFloat operator*(const ExactFloat& a, const ExactFloat& b); |
| 342 | |
| 343 | // Division is not implemented because the result cannot be represented |
| 344 | // exactly in general. Doing this properly would require extending all the |
| 345 | // operations to support rounding to a specified precision. |
| 346 | |
| 347 | // Arithmetic assignment operators (+=, -=, *=). |
| 348 | ExactFloat& operator+=(const ExactFloat& b) { return (*this = *this + b); } |
| 349 | ExactFloat& operator-=(const ExactFloat& b) { return (*this = *this - b); } |
| 350 | ExactFloat& operator*=(const ExactFloat& b) { return (*this = *this * b); } |
| 351 | |
| 352 | // Comparison operators (==, !=, <, <=, >, >=). |
| 353 | friend bool operator==(const ExactFloat& a, const ExactFloat& b); |
| 354 | friend bool operator<(const ExactFloat& a, const ExactFloat& b); |
| 355 | // These don't need to be friends but are declared here for completeness. |
| 356 | inline friend bool operator!=(const ExactFloat& a, const ExactFloat& b); |
| 357 | inline friend bool operator<=(const ExactFloat& a, const ExactFloat& b); |
| 358 | inline friend bool operator>(const ExactFloat& a, const ExactFloat& b); |
| 359 | inline friend bool operator>=(const ExactFloat& a, const ExactFloat& b); |
| 360 | |
| 361 | ///////////////////////////////////////////////////////////////////// |
| 362 | // Math Intrinsics |
| 363 | // |
| 364 | // The math intrinsics currently supported by ExactFloat are listed below. |
| 365 | // Except as noted, they behave identically to the usual glibc intrinsics |
| 366 | // except that they have greater precision. See the man pages for more |
| 367 | // information. |
| 368 | |
| 369 | //////// Miscellaneous simple arithmetic functions. |
| 370 | |
| 371 | // Absolute value. |
| 372 | friend ExactFloat fabs(const ExactFloat& a); |
| 373 | |
| 374 | // Maximum of two values. |
| 375 | friend ExactFloat fmax(const ExactFloat& a, const ExactFloat& b); |
| 376 | |
| 377 | // Minimum of two values. |
| 378 | friend ExactFloat fmin(const ExactFloat& a, const ExactFloat& b); |
| 379 | |
| 380 | // Positive difference: max(a - b, 0). |
| 381 | friend ExactFloat fdim(const ExactFloat& a, const ExactFloat& b); |
| 382 | |
| 383 | //////// Integer rounding functions that return ExactFloat values. |
| 384 | |
| 385 | // Round up to the nearest integer. |
| 386 | friend ExactFloat ceil(const ExactFloat& a); |
| 387 | |
| 388 | // Round down to the nearest integer. |
| 389 | friend ExactFloat floor(const ExactFloat& a); |
| 390 | |
| 391 | // Round to the nearest integer not larger in absolute value. |
| 392 | // For example: f(-1.9) = -1, f(2.9) = 2. |
| 393 | friend ExactFloat trunc(const ExactFloat& a); |
| 394 | |
| 395 | // Round to the nearest integer, rounding halfway cases away from zero. |
| 396 | // For example: f(-0.5) = -1, f(0.5) = 1, f(1.5) = 2, f(2.5) = 3. |
| 397 | friend ExactFloat round(const ExactFloat& a); |
| 398 | |
| 399 | // Round to the nearest integer, rounding halfway cases to an even integer. |
| 400 | // For example: f(-0.5) = 0, f(0.5) = 0, f(1.5) = 2, f(2.5) = 2. |
| 401 | friend ExactFloat rint(const ExactFloat& a); |
| 402 | |
| 403 | // A synonym for rint(). |
| 404 | friend ExactFloat nearbyint(const ExactFloat& a) { return rint(a); } |
| 405 | |
| 406 | //////// Integer rounding functions that return C++ integer types. |
| 407 | |
| 408 | // Like rint(), but rounds to the nearest "long" value. Returns the |
| 409 | // minimum/maximum possible integer if the value is out of range. |
| 410 | friend long lrint(const ExactFloat& a); |
| 411 | |
| 412 | // Like rint(), but rounds to the nearest "long long" value. Returns the |
| 413 | // minimum/maximum possible integer if the value is out of range. |
| 414 | friend long long llrint(const ExactFloat& a); |
| 415 | |
| 416 | // Like round(), but rounds to the nearest "long" value. Returns the |
| 417 | // minimum/maximum possible integer if the value is out of range. |
| 418 | friend long lround(const ExactFloat& a); |
| 419 | |
| 420 | // Like round(), but rounds to the nearest "long long" value. Returns the |
| 421 | // minimum/maximum possible integer if the value is out of range. |
| 422 | friend long long llround(const ExactFloat& a); |
| 423 | |
| 424 | //////// Remainder functions. |
| 425 | |
| 426 | // The remainder of dividing "a" by "b", where the quotient is rounded toward |
| 427 | // zero to the nearest integer. Similar to (a - trunc(a / b) * b). |
| 428 | friend ExactFloat fmod(const ExactFloat& a, const ExactFloat& b) { |
| 429 | // Note that it is possible to implement this operation exactly, it just |
| 430 | // hasn't been done. |
| 431 | return Unimplemented(); |
| 432 | } |
| 433 | |
| 434 | // The remainder of dividing "a" by "b", where the quotient is rounded to the |
| 435 | // nearest integer, rounding halfway cases to an even integer. Similar to |
| 436 | // (a - rint(a / b) * b). |
| 437 | friend ExactFloat remainder(const ExactFloat& a, const ExactFloat& b) { |
| 438 | // Note that it is possible to implement this operation exactly, it just |
| 439 | // hasn't been done. |
| 440 | return Unimplemented(); |
| 441 | } |
| 442 | |
| 443 | // A synonym for remainder(). |
| 444 | friend ExactFloat drem(const ExactFloat& a, const ExactFloat& b) { |
| 445 | return remainder(a, b); |
| 446 | } |
| 447 | |
| 448 | // Break the argument "a" into integer and fractional parts, each of which |
| 449 | // has the same sign as "a". The fractional part is returned, and the |
| 450 | // integer part is stored in the output parameter "i_ptr". Both output |
| 451 | // values are set to have the same maximum precision as "a". |
| 452 | friend ExactFloat modf(const ExactFloat& a, ExactFloat* i_ptr) { |
| 453 | // Note that it is possible to implement this operation exactly, it just |
| 454 | // hasn't been done. |
| 455 | return Unimplemented(); |
| 456 | } |
| 457 | |
| 458 | //////// Floating-point manipulation functions. |
| 459 | |
| 460 | // Return an ExactFloat with the magnitude of "a" and the sign bit of "b". |
| 461 | // (Note that an IEEE zero can be either positive or negative.) |
| 462 | friend ExactFloat copysign(const ExactFloat& a, const ExactFloat& b); |
| 463 | |
| 464 | // Convert "a" to a normalized fraction in the range [0.5, 1) times a power |
| 465 | // of two. Return the fraction and set "exp" to the exponent. If "a" is |
| 466 | // zero, infinity, or NaN then return "a" and set "exp" to zero. |
| 467 | friend ExactFloat frexp(const ExactFloat& a, int* exp); |
| 468 | |
| 469 | // Return "a" multiplied by 2 raised to the power "exp". |
| 470 | friend ExactFloat ldexp(const ExactFloat& a, int exp); |
| 471 | |
| 472 | // A synonym for ldexp(). |
| 473 | friend ExactFloat scalbn(const ExactFloat& a, int exp) { |
| 474 | return ldexp(a, exp); |
| 475 | } |
| 476 | |
| 477 | // A version of ldexp() where "exp" is a long integer. |
| 478 | friend ExactFloat scalbln(const ExactFloat& a, long exp) { |
| 479 | return ldexp(a, exp); |
| 480 | } |
| 481 | |
| 482 | // Convert "a" to a normalized fraction in the range [1,2) times a power of |
| 483 | // two, and return the exponent value as an integer. This is equivalent to |
| 484 | // lrint(floor(log2(fabs(a)))) but it is computed more efficiently. Returns |
| 485 | // the constants documented in the man page for zero, infinity, or NaN. |
| 486 | friend int ilogb(const ExactFloat& a); |
| 487 | |
| 488 | // Convert "a" to a normalized fraction in the range [1,2) times a power of |
| 489 | // two, and return the exponent value as an ExactFloat. This is equivalent to |
| 490 | // floor(log2(fabs(a))) but it is computed more efficiently. |
| 491 | friend ExactFloat logb(const ExactFloat& a); |
| 492 | |
| 493 | protected: |
| 494 | // Non-normal numbers are represented using special exponent values and a |
| 495 | // mantissa of zero. Do not change these values; methods such as |
| 496 | // is_normal() make assumptions about their ordering. Non-normal numbers |
| 497 | // can have either a positive or negative sign (including zero and NaN). |
| 498 | static const int32 kExpNaN = INT_MAX; |
| 499 | static const int32 kExpInfinity = INT_MAX - 1; |
| 500 | static const int32 kExpZero = INT_MAX - 2; |
| 501 | |
| 502 | // Normal numbers are represented as (sign_ * bn_ * (2 ** bn_exp_)), where: |
| 503 | // - sign_ is either +1 or -1 |
| 504 | // - bn_ is a BIGNUM with a positive value |
| 505 | // - bn_exp_ is the base-2 exponent applied to bn_. |
| 506 | int32 sign_; |
| 507 | int32 bn_exp_; |
| 508 | BIGNUM bn_; |
| 509 | |
| 510 | // A standard IEEE "double" has a 53-bit mantissa consisting of a 52-bit |
| 511 | // fraction plus an implicit leading "1" bit. |
| 512 | static const int kDoubleMantissaBits = 53; |
| 513 | |
| 514 | // Convert an ExactFloat with no more than 53 bits in its mantissa to a |
| 515 | // "double". This method handles non-normal values (NaN, etc). |
| 516 | double ToDoubleHelper() const; |
| 517 | |
| 518 | // Round an ExactFloat so that it is a multiple of (2 ** bit_exp), using the |
| 519 | // given rounding mode. |
| 520 | ExactFloat RoundToPowerOf2(int bit_exp, RoundingMode mode) const; |
| 521 | |
| 522 | // Convert the ExactFloat to a decimal value of the form 0.ddd * (10 ** x), |
| 523 | // with at most "max_digits" significant digits (trailing zeros are removed). |
| 524 | // Set (*digits) to the ASCII digits and return the decimal exponent "x". |
| 525 | int GetDecimalDigits(int max_digits, string* digits) const; |
| 526 | |
| 527 | // Return a_sign * fabs(a) + b_sign * fabs(b). Used to implement addition |
| 528 | // and subtraction. |
| 529 | static ExactFloat SignedSum(int a_sign, const ExactFloat* a, |
| 530 | int b_sign, const ExactFloat* b); |
| 531 | |
| 532 | // Convert an ExactFloat to its canonical form. Underflow results in signed |
| 533 | // zero, overflow results in signed infinity, and precision overflow results |
| 534 | // in NaN. A zero mantissa is converted to the canonical zero value with |
| 535 | // the given sign; otherwise the mantissa is normalized so that its low bit |
| 536 | // is 1. Non-normal numbers are left unchanged. |
| 537 | void Canonicalize(); |
| 538 | |
| 539 | // Scale the mantissa of this ExactFloat so that it has the same bn_exp_ as |
| 540 | // "b", then return -1, 0, or 1 according to whether the scaled mantissa is |
| 541 | // less, equal, or greater than the mantissa of "b". Requires that both |
| 542 | // values are normal. |
| 543 | int ScaleAndCompare(const ExactFloat& b) const; |
| 544 | |
| 545 | // Return true if the magnitude of this ExactFloat is less than the |
| 546 | // magnitude of "b". Requires that neither value is NaN. |
| 547 | bool UnsignedLess(const ExactFloat& b) const; |
| 548 | |
| 549 | // Return an ExactFloat with the magnitude of this ExactFloat and the given |
| 550 | // sign. (Similar to copysign, except that the sign is given explicitly |
| 551 | // rather than being copied from another ExactFloat.) |
| 552 | inline ExactFloat CopyWithSign(int sign) const; |
| 553 | |
| 554 | // Convert an ExactFloat to an integer of type "T" using the given rounding |
| 555 | // mode. The type "T" must be signed. Returns the largest possible integer |
| 556 | // for NaN, and clamps out of range values to the largest or smallest |
| 557 | // possible values. |
| 558 | template <class T> T ToInteger(RoundingMode mode) const; |
| 559 | |
| 560 | // Log a fatal error message (used for unimplemented methods). |
| 561 | static ExactFloat Unimplemented(); |
| 562 | }; |
| 563 | |
| 564 | ///////////////////////////////////////////////////////////////////////// |
| 565 | // Implementation details follow: |
| 566 | |
| 567 | inline ExactFloat::ExactFloat() : sign_(1), bn_exp_(kExpZero) { |
| 568 | BN_init(&bn_); |
| 569 | } |
| 570 | |
| 571 | inline ExactFloat::~ExactFloat() { |
| 572 | BN_free(&bn_); |
| 573 | } |
| 574 | |
| 575 | inline bool ExactFloat::is_zero() const { return bn_exp_ == kExpZero; } |
| 576 | inline bool ExactFloat::is_inf() const { return bn_exp_ == kExpInfinity; } |
| 577 | inline bool ExactFloat::is_nan() const { return bn_exp_ == kExpNaN; } |
| 578 | inline bool ExactFloat::is_normal() const { return bn_exp_ < kExpZero; } |
| 579 | inline bool ExactFloat::is_finite() const { return bn_exp_ <= kExpZero; } |
| 580 | inline bool ExactFloat::sign_bit() const { return sign_ < 0; } |
| 581 | |
| 582 | inline int ExactFloat::sgn() const { |
| 583 | return (is_nan() || is_zero()) ? 0 : sign_; |
| 584 | } |
| 585 | |
| 586 | inline bool operator!=(const ExactFloat& a, const ExactFloat& b) { |
| 587 | return !(a == b); |
| 588 | } |
| 589 | |
| 590 | inline bool operator<=(const ExactFloat& a, const ExactFloat& b) { |
| 591 | // NaN is unordered compared to everything, including itself. |
| 592 | if (a.is_nan() || b.is_nan()) return false; |
| 593 | return !(b < a); |
| 594 | } |
| 595 | |
| 596 | inline bool operator>(const ExactFloat& a, const ExactFloat& b) { |
| 597 | return b < a; |
| 598 | } |
| 599 | |
| 600 | inline bool operator>=(const ExactFloat& a, const ExactFloat& b) { |
| 601 | return b <= a; |
| 602 | } |
| 603 | |
| 604 | inline ExactFloat ExactFloat::CopyWithSign(int sign) const { |
| 605 | ExactFloat r = *this; |
| 606 | r.sign_ = sign; |
| 607 | return r; |
| 608 | } |
| 609 | |
| 610 | #endif // UTIL_MATH_EXACTFLOAT_EXACTFLOAT_H_ |
| 611 | |