PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

fixed point wrapper object?

Hi,


Is there a good reason why I shouldn’t write a fixed point wrapper object class to help with ease of type checking and programming, (I noticed they had one in allegro) it should be efficient with inlines, I thought id ask rather than just wade in and find later that’s not case.
I actually always wonder why people are still using macros for fixed point maths =)
Thierry wrote:I actually always wonder why people are still using macros for fixed point maths =)

Because you loose control over the inlining behavior... also the semantics for intermediate 64-bit results (like accumulation of products) don't map nicely into a simple wrapper class. Other than that, there is really no reason... ;-)

-HM
Structure wrote:Hi,


Is there a good reason why I shouldn’t write a fixed point wrapper object class to help with ease of type checking and programming, (I noticed they had one in allegro) it should be efficient with inlines, I thought id ask rather than just wade in and find later that’s not case.

Here you go. The missing functions are the ones from the implementation you already seem to be using.

- HM
Code:

class Fixed {

enum {
PRECISION = 16,
ONE = 0x10000
};

explicit Fixed(Int32 anInt, bool) {
m_value = anInt;
}

public:
Fixed() {
}

Fixed(const Fixed& other) {
m_value = other.m_value;
}

Fixed(Float aFloat) {
m_value = static_cast<Int32>(aFloat * static_cast<Float>(ONE));
}

Fixed(Int32 anInt) {
m_value = anInt << PRECISION;
}

operator Int32() const {
return m_value >> PRECISION;
}

operator Float() const {
return m_value * (1.0f/static_cast<Float>(ONE));
}

static Fixed FromValue(Int32 aValue) {
return Fixed(aValue, true);
}

Bool operator==(const Fixed& other) const {
return m_value == other.m_value;
}

Bool operator!=(const Fixed& other) const {
return m_value != other.m_value;
}

Bool operator<(const Fixed& other) const {
return m_value < other.m_value;
}

Bool operator>(const Fixed& other) const {
return m_value > other.m_value;
}

Bool operator<=(const Fixed& other) const {
return m_value <= other.m_value;
}

Bool operator>=(const Fixed& other) const {
return m_value >= other.m_value;
}

Fixed operator-() const {
return Fixed(-m_value, true);
}

Fixed operator+(const Fixed& other) const {
return Fixed(m_value + other.m_value, true);
}

Fixed operator-(const Fixed& other) const {
return Fixed(m_value - other.m_value, true);
}

Fixed operator*(const Fixed& other) const {
return Fixed(static_cast<Int32>(((Int64) m_value * (Int64) other.m_value) >> PRECISION), true);
}

Fixed operator/(const Fixed& other) const {
return *this * other.Inverse();
}

Fixed& operator=(const Fixed& other) {
m_value = other.m_value;
return *this;
}

Fixed& operator+=(const Fixed& other) {
m_value += other.m_value;
return *this;
}

Fixed& operator-=(const Fixed& other) {
m_value -= other.m_value;
return *this;
}

Fixed& operator*=(const Fixed& other) {
m_value = static_cast<Int32>(((Int64) m_value * (Int64) other.m_value) >> PRECISION);
return *this;
}

Fixed& operator/=(const Fixed& other) {
return *this *= other.Inverse();
}

Fixed Inverse() const;

Int32 Value() const {
return m_value;
}

static Fixed Sin(const Fixed & value);
static Fixed Cos(const Fixed & value);
static Fixed Sqrt(const Fixed & value);
static Fixed InvSqrt(const Fixed & value);
static Fixed Abs(const Fixed & value);
static Fixed Sgn(const Fixed & value);
static Fixed Fraction(const Fixed & value);
static Fixed Inverse(const Fixed & value);

private:
Int32 m_value;
};

inline Fixed Fixed::Abs(const Fixed & value) {
return value.m_value >= 0 ? value : -value;
}

inline Fixed Fixed::Sgn(const Fixed & value) {
if (value.m_value > 0) {
return Fixed(1);
} else if (value.m_value < 0) {
return Fixed(-1);
} else {
return Fixed(0);
}
}

inline Fixed Fixed::Sqrt(const Fixed & value) {
return InvSqrt(value).Inverse();
}

inline Fixed Fixed::Fraction(const Fixed & value) {
return Fixed(value.m_value & ((1 << PRECISION) - 1), true);
}

inline Fixed Fixed::Inverse(const Fixed & value) {
return value.Inverse();
}

hm wrote:Because you loose control over the inlining behavior...


You are wrong on this one. I've verified that every method of my fixed class was inlined. I don't see any problem there.

hm wrote:also the semantics for intermediate 64-bit results (like accumulation of products) don't map nicely into a simple wrapper class.


And why not? I'll agree it requires a little more time to properly wrap a fixed number in a class. But it will save you more time in the end then it is going to take you writing it.
Thierry":1sge1p1f]
hm wrote:Because you loose control over the inlining behavior...


You are wrong on this one. I've verified that every method of my fixed class was inlined. I don't see any problem there.
Thierry, not everyone is working one the same program as you do... ;-)

Thierry wrote:[quote="hm wrote:also the semantics for intermediate 64-bit results (like accumulation of products) don't map nicely into a simple wrapper class.


And why not? I'll agree it requires a little more time to properly wrap a fixed number in a class. But it will save you more time in the end then it is going to take you.


Take the example of normalizing a vector (i.e. without overflow): You probably have this function rather in your vector class than in your fixed point primitive. So how do you go about writing it in the implementation of the vector class? Maybe the macros are good building blocks for that.

Or take a matrix inversion? Wouldn't that fit much better in a matrix class? How about color format conversion with correct rounding? I rather put this stuff in my color class than exploding the fixed point wrapper class.

You asked why people use macros. These are the reasons I do: in many cases, there are better high-level abstractions, and using the primitive class is not always the best way to sufficient precision and performance.

- HM
hm wrote:Thierry, not everyone is working one the same program as you do... ;-)


I do not follow you. My fixed class works very well in every program. It is also being used in our code base at work.

hm wrote:Take the example of normalizing a vector (i.e. without overflow): You probably have this function rather in your vector class than in your fixed point primitive. So how do you go about writing it in the implementation of the vector class?


Again I do not follow you. To normalize a vector, I just divide it by its length. All the maths are done using the fixed point class:

Code:

struct Vector3
{
Fixed x,y,z;
void Normalize()
{
Fixed t = Fixed(1) / sqrt( x*x+y*y+z*z );
x *= t; y *= t; z *= t;
}
};


I am assuming all the operators are properly overloaded and sqrt() defined for Fixed. It works here anyways (+/- some precision issues that I haven't illustrated above).

hm wrote:Maybe the macros are good building blocks for that.


Macros are evil. Period. They should only be used for include guards and configuration (platform, compiler, etc). You don't need them for anything else in C++.

hm wrote:Or take a matrix inversion? Wouldn't that fit much better in a matrix class? How about color format conversion with correct rounding? I rather put this stuff in my color class than exploding the fixed point wrapper class.


Again just provide the proper operator overloads and you can use normal maths in any class you want (matrix, color, etc). I don't understand why/how your Fixed class would become bloated.

hm wrote:You asked why people use macros. These are the reasons I do: in many cases, there are better high-level abstractions,


They never are.

hm wrote:and using the primitive class is not always the best way to sufficient precision and performance.


Here I would agree. But using helper functions and/or closure constructs, you can solve these problems in a type-safe manner without resorting to macros.
Thierry I do not want to go into a lengthy discussion here, so let me just comment on your code example:
Code:

struct Vector3
{
Fixed x,y,z;
void Normalize()
{
Fixed t = Fixed(1) / sqrt( x*x+y*y+z*z );
x *= t; y *= t; z *= t;
}
};

If x, y and z are fixed numbers (S15.16), then the intermediate result of your multiplication is not going to fit into a 32-bit number (which, by the way, is exactly the problem earlier posted in this forum, right?). You have two routes to proceed from here: a.) You artificially restrict the valid range of your coordinates to values that do not guarantee any overflow in your specific implementation for the sake of 'doing it right'. b.) You take a step back and turn the whole "normalize" function into a primitive that is both efficient and has the required numerical characteristics. Even though your fixed point class cannot express this, your products are already calculated as 64-bit intermediates, and it is straightfoward to accumulate them as a 64-bit value as well. The typical sqrt (or invsqrt, which is what I would use right away, it has better convergence) implementation starts out by shifting the input value into a suitable range. So once you determined your shift value, you can go back to regular arithmetic.

The point is simply that there are applications where this kind of attention to numerical detail is relevant.

Cheers,
HM
OK, here is a more detailled example of what I meant:

Code:


//////////////////////////////////////////////////////////////////////////////
//
// Fixed32: 32.32 fixed point number
//
//////////////////////////////////////////////////////////////////////////////

class Fixed32
{
public:

Fixed32() {}
explicit Fixed32( int32_t i ) : v( i << 32 ) {}
static Fixed32 FromRaw( int64_t raw ) { Fixed32 r; r.v = raw; return r; }
int64_t Raw() const { return v; }

private:
int64_t v;
};



//////////////////////////////////////////////////////////////////////////////
//
// Fixed16: 16.16 fixed point number
//
//////////////////////////////////////////////////////////////////////////////

class Fixed16
{
public:

Fixed16() {}
explicit Fixed16( int16_t i ) : v( i << 16 ) {}
Fixed16( Fixed32 f32 ) : v( int32_t(f32.Raw() >> 16) ) {}
static Fixed16 FromRaw( int32_t raw ) { Fixed16 r; r.v = raw; return r; }
int32_t Raw() const { return v; }

private:
int32_t v;
};



inline Fixed32 operator*( Fixed16 a, Fixed16 b )
{
return Fixed32::FromRaw( int64_t(a.Raw()) * b.Raw() );
}


Then you can do:

Code:

Fixed16 a(4);
Fixed16 b(5);
Fixed16 c = a * b;


And this without losing any precision. You also get type safety.

The basic idea is that operator* is defined as taking in two fixed 16.16 numbers and returning a fixed 32.32 one. If you decide to assign that to another fixed 16.16 number, the conversion is implicit. Therefore, the final code becomes exactly what you want it to be.

Similar code can be used for all math operations (sqrt, cos, sin, etc).

You can even add some nice operators like this:

Code:

class Fixed16
{
...
Fixed16& operator*=( int rhs )
{
v *= rhs;
return *this;
}

Fixed16& operator*=( Fixed16 rhs )
{
v = int32_t((int64_t(v) * rhs.v) >> 16);
return *this;
}
...
}


I maintain that there is nothing a macro will give you over properly written operators.

I am even in the process of extending my code to support arbitrary precision numbers so that you can do stuff like:

Code:

Fixed<8,8> a,b;
Fixed<16,16> c = a * b;


With proper code, this should generate a simple 32*32 bits multiplication with no need for shifts/overflow checks.

hm wrote:
The point is simply that there are applications where this kind of attention to numerical detail is relevant.


I know far more about numerical methods then you think. That's what I do for a living.
Thierry wrote:I know far more about numerical methods then you think. That's what I do for a living.


/me Starting to get that idea... ;)

Thanks for the very informative post. I really have tried to stay away from exactly what you are doing... and you've pretty much changed my mind. Considering the amount of fixed point math in the physics for our next game... this could be an important concept. I've always worried about the overhead involved in doing such a wrapper with operators, but I guess I'll have to test this myself. In addition, we've run into problems with really crappy compilers on other platforms, so we've always tried to stay away from anything more complicated than 2+2=4.... but compilers are getting better on even the lowest level devices, so maybe now is the time to change. Goodness knows creating original code is bad enough in fixed point and porting floating point is more like a nightmare. This would be an interesting way to get the bulk of the code up and running and then chase after precision errors on a case by case basis (which you have to do anyway).
Thierry wrote:OK, here is a more detailled example of what I meant:
Thanks!

- HM
Thanks guys this has been a very insightful debate, exactly what I was after.

And thanks for al the code examples, that was fantastic.