PocketMatrix forums

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

EasyCE / vector length

Dave Johnston · 29 May 2002, 17:21 UTC
Consider the following (mocked-up) values:
int x = FP(20.5);
int y = FP(12.5);

Now, suppose these represented a 2d vector. I would find the length of the vector using Pythag's theoreom:

len = sqrt(x^2 + y^2);

Hence:

float xx = ( ((float)FPMUL(x, x) - 0.5f) / FP_ONE );
float yy = ( ((float)FPMUL(y, y) - 0.5f) / FP_ONE );
int length = FP(sqrt(xx + yy));

By my reckoning, 'length' should represent the length of the vector. But... according to my tests, it doesn't. More often than not, the result is 0, or a power of 2.

I for the life of me can't work out what's going on, I think it's one of those bugs that it so glaringly obvious you don't see it.

Can anyone see anything wrong? If not, I'll assume I need to do more digging in my code... but it's REALLY confused me. I won't post the code - I'm certain enough that the code above is the problem.
Dave Johnston · 29 May 2002, 17:30 UTC
Grr, trust it to start working now.

Sometimes programming is as unpredictable as England's weather...

Now I just have to ensure it really is giving me the right results (not constant 0's...)
You may be able to get by without converting to floats if you don't mind losing either half the fractional precision or half the integer precision. If you simply multiply the fixed-point values without shifting back, when you take the square root, the "decimal point" will return to the correct location. By the same token, if you need integer precision more than fractional precision, use the FPMUL macro and shift the sqrt result left by FPP/2 (5 by default). Obviously this would be much less precise, but it would be much faster without the floating point stuff, and you could also then use an integer square root instead of a floating point one.

In other words:
Code:

int x=FP(20.5);
int y=FP(12.5);
int xx=x*x;
int yy=y*y;
int length=sqrt(xx+yy);

or
Code:

int x=FP(20.5);
int y=FP(12.5);
int xx=FPMUL(x,x);
int yy=FPMUL(y,y);
int length=sqrt(xx+yy)>>5;
Dave Johnston · 29 May 2002, 23:24 UTC
Hmm, very cunning... I hadn't got round to thinking about optimising yet, but even still, wouldn't have spotted that...

Thanks for the tip!

In case anyone cares, this is all for a simple bounding box collision/bounce routine. I've got them footballs bouncing at last! (40 or so footballs, random velocity on screen, bouncing off one another... 35fps isn't bad IMO).

Still need to work out why ASurface crashes and/or gives a black pixel array on initialisation with my background image though...