# Fixed point math routines

• fixacos — Fixed point inverse cosine lookup table.
• fixadd — Safe function to add fixed point numbers clamping overflow.
• fixasin — Fixed point inverse sine lookup table.
• fixatan — Fixed point inverse tangent lookup table.
• fixatan2 — Fixed point version of the libc atan2() routine.
• fixceil — Returns the smallest integer not less than x.
• fixcos — Fixed point cosine of binary angles.
• fixdiv — Fixed point division.
• fixfloor — Returns the greatest integer not greater than x.
• fixhypot — Fixed point hypotenuse.
• fixmul — Multiplies two fixed point values together.
• fixsin — Fixed point sine of binary angles.
• fixsqrt — Fixed point square root.
• fixsub — Safe function to subtract fixed point numbers clamping underflow.
• fixtan — Fixed point tangent of binary angles.
• fixtof — Converts a fixed point to floating point.
• fixtoi — Converts a fixed point to integer with rounding.
• fixtorad_r — Constant to convert angles in fixed point format to radians.
• ftofix — Converts a floating point value to fixed point.
• itofix — Converts an integer to fixed point.

Allegro provides some routines for working with fixed point numbers, and defines the type `fixed' to be a signed 32-bit integer. The high word is used for the integer part and the low word for the fraction, giving a range of -32768 to 32767 and an accuracy of about four or five decimal places. Fixed point numbers can be assigned, compared, added, subtracted, negated and shifted (for multiplying or dividing by powers of two) using the normal integer operators, but you should take care to use the appropriate conversion routines when mixing fixed point with integer or floating point values. Writing `fixed_point_1 + fixed_point_2' is OK, but `fixed_point + integer' is not.

Unfortunately the only advantage of fixed point math routines is that you don't require a floating point coprocessor to use them. This was great in the time period of i386 and i486 machines, but stopped being so useful with the coming of the Pentium class of processors. From Pentium onwards, CPUs have increased their strength in floating point operations, equaling or even surpassing integer math performance.

Depending on the type of operations your program may need, using floating point types may be faster than fixed types if you are targeting a specific machine class. Allegro comes with a test program in the `allegro/tests' directory. Its `Misc' menu contains a basic profile test which can give you an idea of the speed difference between fixed and float types for a few basic operations on your machine. However, don't forget to profile your program in real life conditions, tight loop benchmarks are after all artificial.

Fixed point math is considered "add-on" material and is kept only for backwards compatibility. Whenever a future release of Allegro breaks backwards compatibility, fixed point math will likely be moved to a separate add-on package for the very few users who still find it convenient and useful, and Allegro functions using fixed point math will use other types.

fixed itofix(int x);

Converts an integer to fixed point. This is the same thing as x<<16. Remember that overflows (trying to convert an integer greater than 32767) and underflows (trying to convert an integer lesser than -32768) are not detected even in debug builds! The values simply "wrap around". Example:
```      fixed number;
/* This conversion is OK. */
number = itofix(100);
ASSERT(fixtoi(number) == 100);
number = itofix(64000);
/* This check will fail in debug builds. */
ASSERT(fixtoi(number) == 64000);```

Return value: Returns the value of the integer converted to fixed point ignoring overflows.

Examples using this: ex12bit, ex3buf, ex3d, exblend, excustom, exfixed, exlights, exspline, exsprite, exstars.
int fixtoi(fixed x);

Converts fixed point to integer, rounding as required to the nearest integer. Example:
```      int result;
/* This will put 33 into `result'. */
result = fixtoi(itofix(100) / 3);
/* But this will round up to 17. */
result = fixtoi(itofix(100) / 6);```
Examples using this: ex12bit, ex3buf, ex3d, exblend, excustom, exlights, exspline, exstars, exupdate.
int fixfloor(fixed x);

Returns the greatest integer not greater than x. That is, it rounds towards negative infinity. Example:
```      int result;
/* This will put 33 into `result'. */
result = fixfloor(itofix(100) / 3);
/* And this will round down to 16. */
result = fixfloor(itofix(100) / 6);```
int fixceil(fixed x);

Returns the smallest integer not less than x. That is, it rounds towards positive infinity. Example:
```      int result;
/* This will put 34 into `result'. */
result = fixceil(itofix(100) / 3);
/* This will round up to 17. */
result = fixceil(itofix(100) / 6);```
fixed ftofix(double x);

Converts a floating point value to fixed point. Unlike itofix(), this function clamps values which could overflow the type conversion, setting `errno' to ERANGE in the process if this happens. Example:
```      fixed number;
number = itofix(-40000);
ASSERT(fixfloor(number) == -32768);
number = itofix(64000);
ASSERT(fixfloor(number) == 32767);
ASSERT(!errno); /* This will fail. */```

Return value: Returns the value of the floating point value converted to fixed point clamping overflows (and setting `errno').

Examples using this: exfixed, exrotscl, exspline, exupdate.
double fixtof(fixed x);

Converts fixed point to floating point. Example:
```      float result;

/* This will put 33.33333 into `result'. */
result = fixtof(itofix(100) / 3);
/* This will put 16.66666 into `result'. */
result = fixtof(itofix(100) / 6);```
Examples using this: exfixed, exspline, exstars.
fixed fixmul(fixed x, fixed y);

A fixed point value can be multiplied or divided by an integer with the normal `*' and `/' operators. To multiply two fixed point values, though, you must use this function.

If an overflow occurs, `errno' will be set and the maximum possible value will be returned, but `errno' is not cleared if the operation is successful. This means that if you are going to test for overflow you should set `errno=0' before calling fixmul(). Example:

```      fixed result;

/* This will put 30000 into `result'. */
result = fixmul(itofix(10), itofix(3000));
/* But this overflows, and sets `errno'. */
result = fixmul(itofix(100), itofix(3000));
ASSERT(!errno);```

Return value: Returns the clamped result of multiplying `x' by `y', setting `errno' to ERANGE if there was an overflow.

Examples using this: ex3buf, excustom, exfixed, exspline, exstars, exupdate.
fixed fixdiv(fixed x, fixed y);

A fixed point value can be divided by an integer with the normal `/' operator. To divide two fixed point values, though, you must use this function. If a division by zero occurs, `errno' will be set and the maximum possible value will be returned, but `errno' is not cleared if the operation is successful. This means that if you are going to test for division by zero you should set `errno=0' before calling fixdiv(). Example:
```      fixed result;
/* This will put 0.06060 `result'. */
result = fixdiv(itofix(2), itofix(33));
/* This will put 0 into `result'. */
result = fixdiv(0, itofix(-30));
/* Sets `errno' and puts -32768 into `result'. */
result = fixdiv(itofix(-100), itofix(0));
ASSERT(!errno); /* This will fail. */```

Return value: Returns the result of dividing `x' by `y'. If `y' is zero, returns the maximum possible fixed point value and sets `errno' to ERANGE.

Examples using this: exfixed.

Although fixed point numbers can be added with the normal '+' integer operator, that doesn't provide any protection against overflow. If overflow is a problem, you should use this function instead. It is slower than using integer operators, but if an overflow occurs it will set `errno' and clamp the result, rather than just letting it wrap. Example:
```      fixed result;
/* This will put 5035 into `result'. */
/* Sets `errno' and puts -32768 into `result'. */
ASSERT(!errno); /* This will fail. */```

Return value: Returns the clamped result of adding `x' to `y', setting `errno' to ERANGE if there was an overflow.

fixed fixsub(fixed x, fixed y);

Although fixed point numbers can be subtracted with the normal '-' integer operator, that doesn't provide any protection against overflow. If overflow is a problem, you should use this function instead. It is slower than using integer operators, but if an overflow occurs it will set `errno' and clamp the result, rather than just letting it wrap. Example:
```      fixed result;
/* This will put 4965 into `result'. */
result = fixsub(itofix(5000), itofix(35));
/* Sets `errno' and puts -32768 into `result'. */
result = fixsub(itofix(-31000), itofix(3000));
ASSERT(!errno); /* This will fail. */```

Return value: Returns the clamped result of subtracting `y' from `x', setting `errno' to ERANGE if there was an overflow.

## Fixed point trig

The fixed point square root, sin, cos, tan, inverse sin, and inverse cos functions are implemented using lookup tables, which are very fast but not particularly accurate. At the moment the inverse tan uses an iterative search on the tan table, so it is a lot slower than the others. Note that on machines with very good floating point processors using these functions could be slower in real life code due to cache misses: it may be faster to wait a few extra cycles for a floating point sine result rather than wait for the CPU to fetch the precalculated table from main memory. Always profile your code.

Angles are represented in a binary format with 256 equal to a full circle, 64 being a right angle and so on. This has the advantage that a simple bitwise 'and' can be used to keep the angle within the range zero to a full circle, eliminating all those tiresome 'if (angle >= 360)' checks.

This constant gives a ratio which can be used to convert a fixed point number in binary angle format to a fixed point number in radians. Example:
```      fixed rad_angle, binary_angle;
/* Set the binary angle to 90 degrees. */
binary_angle = 64;

This constant gives a ratio which can be used to convert a fixed point number in radians to a fixed point number in binary angle format. Example:
```      fixed rad_angle, binary_angle;
...
fixed fixsin(fixed x);

This function finds the sine of a value using a lookup table. The input value must be a fixed point binary angle. Example:
```      fixed angle;
int result;

/* Set the binary angle to 90 degrees. */
angle = itofix(64);
/* The sine of 90 degrees is one. */
result = fixtoi(fixsin(angle));
ASSERT(result == 1);```

Return value: Returns the sine of a fixed point binary format angle. The return value will be in radians.

Examples using this: ex12bit, ex3buf, exblend, excustom, exspline, exupdate.
fixed fixcos(fixed x);

This function finds the cosine of a value using a lookup table. The input value must be a fixed point binary angle. Example:
```      fixed angle;
float result;

/* Set the binary angle to 45 degrees. */
angle = itofix(32);
/* The cosine of 45 degrees is about 0.7071. */
result = fixtof(fixcos(angle));
ASSERT(result > 0.7 && result < 0.71);```

Return value: Returns the cosine of a fixed point binary format angle. The return value will be in radians.

Examples using this: ex12bit, ex3buf, exblend, excustom, exspline, exupdate.
fixed fixtan(fixed x);

This function finds the tangent of a value using a lookup table. The input value must be a fixed point binary angle. Example:
```      fixed angle, res_a, res_b;
float dif;

angle = itofix(37);
/* Prove that tan(angle) == sin(angle) / cos(angle). */
res_a = fixdiv(fixsin(angle), fixcos(angle));
res_b = fixtan(angle);
dif = fixtof(fixsub(res_a, res_b));
allegro_message("Precision error: %f\n", dif);```

Return value: Returns the tangent of a fixed point binary format angle. The return value will be in radians.

fixed fixasin(fixed x);

This function finds the inverse sine of a value using a lookup table. The input value must be a fixed point value. The inverse sine is defined only in the domain from `-1' to `1'. Outside of this input range, the function will set `errno' to EDOM and return zero. Example:
```      float angle;
fixed val;

/* Sets `val' to a right binary angle (`64'). */
val = fixasin(itofix(1));
/* Sets `angle' to 0.2405. */
/* This will trigger the assert. */
val = fixasin(ftofix(-1.09));
ASSERT(!errno);```

Return value: Returns the inverse sine of a fixed point value, measured as fixed point binary format angle, or zero if the input was out of the range. All return values of this function will be in the range `-64' to `64'.

fixed fixacos(fixed x);

This function finds the inverse cosine of a value using a lookup table. The input value must be a fixed point radian. The inverse cosine is defined only in the domain from `-1' to `1'. Outside of this input range, the function will set `errno' to EDOM and return zero. Example:
```      fixed result;

/* Sets `result' to binary angle 128. */
result = fixacos(itofix(-1));```

Return value: Returns the inverse sine of a fixed point value, measured as fixed point binary format angle, or zero if the input was out of range. All return values of this function will be in the range `0' to `128'.

fixed fixatan(fixed x);

This function finds the inverse tangent of a value using a lookup table. The input value must be a fixed point radian. The inverse tangent is the value whose tangent is `x'. Example:
```      fixed result;

/* Sets `result' to binary angle 13. */
result = fixatan(ftofix(0.326));```

Return value: Returns the inverse tangent of a fixed point value, measured as a fixed point binary format angle.

fixed fixatan2(fixed y, fixed x);

This is a fixed point version of the libc atan2() routine. It computes the arc tangent of `y / x', but the signs of both arguments are used to determine the quadrant of the result, and `x' is permitted to be zero. This function is useful to convert Cartesian coordinates to polar coordinates. Example:
```      fixed result;

/* Sets `result' to binary angle 64. */
result = fixatan2(itofix(1), 0);
/* Sets `result' to binary angle -109. */
result = fixatan2(itofix(-1), itofix(-2));
/* Fails the assert. */
result = fixatan2(0, 0);
ASSERT(!errno);```

Return value: Returns the arc tangent of `y / x' in fixed point binary format angle, from `-128' to `128'. If both `x' and `y' are zero, returns zero and sets `errno' to EDOM.

Examples using this: exlights, exspline.
fixed fixsqrt(fixed x);

This finds out the non negative square root of `x'. If `x' is negative, `errno' is set to EDOM and the function returns zero.
Examples using this: exfixed, exlights, exspline.
fixed fixhypot(fixed x, fixed y);

Fixed point hypotenuse (returns the square root of `x*x + y*y'). This should be better than calculating the formula yourself manually, since the error is much smaller.

## Fix class

If you are programming in C++ you can ignore all the above and use the fix class instead, which overloads a lot of operators to provide automatic conversion to and from integer and floating point values, and calls the above routines as they are required. You should not mix the fix class with the fixed typedef though, because the compiler will mistake the fixed values for regular integers and insert unnecessary conversions. For example, if x is an object of class fix, calling fixsqrt(x) will return the wrong result. You should use the overloaded sqrt(x) or x.sqrt() instead.

On top of that, the Fix class may be slower than using directly the C functions because of implicit internal conversions from one type to another which you otherwise could avoid or minimise. Finally, this is the only bit of C++ in the whole Allegro library, and the developers are certainly going to move it into add-on space in the next version of Allegro which breaks source backwards compatibility.

Back to contents