November 2005
Beginner to intermediate
594 pages
16h 23m
English
You want to perform computations on real numbers using a fixed-point representation of a real number rather than using a floating-point type.
Example 11-40 provides the
implementation of a fixed-point real number, where the number of places to the right of
the binary point is a template parameter. For instance basic_fixed_real<10> has 10 binary digits to the right of the binary
point, allowing it to represent numbers up to a precision of 1/1,024.
Example 11-40. Representing real numbers using a fixed-point implementation
#include <iostream> using namespace std; template<int E> struct BasicFixedReal { typedef BasicFixedReal self; static const int factor = 1 << (E - 1); BasicFixedReal() : m(0) { } BasicFixedReal(double d) : m(static_cast<int>(d * factor)) { } self& operator+=(const self& x) { m += x.m; return *this; } self& operator-=(const self& x) { m -= x.m; return *this; } self& operator*=(const self& x) { m *= x.m; m >>= E; return *this; } self& operator/=(const self& x) { m /= x.m; m *= factor; return *this; } self& operator*=(int x) { m *= x; return *this; } self& operator/=(int x) { m /= x; return *this; } self operator-() { return self(-m); } double toDouble() const { return double(m) / factor; } // friend functions friend self operator+(self x, const self& y) { return x += y; } friend self operator-(self x, const self& y) { return x -= y; } friend self operator*(self x, const self& y) { return x *= y; } friend self operator/(self ...