Code sample: Using fixed-point arithmetic
The following code sample demonstrates how you can and cannot use the Fixed32 class for addition, subtraction, multiplication, division, value conversion, and trigonometry.
import net.rim.device.api.math.*;
public class demoFixed32
{
demoFixed32()
{
// convert an integer to fixed-point
int n = Fixed32.toFP(7); // 7.0
// convert a quantity in ten-thousandths to fixed-point
int m = Fixed32.tenThouToFP(70625); // 7.0625
// convert from fixed-point, truncate fractional component
int trunc = Fixed32.toInt(m); // 7
// multiply by ten thousand
int mult = Fixed32.toIntTenThou(m); // 70625
// add, subtract, negate, and compare
int result = m - n; // 7.0625 - 7.0 == 0.0625
result = -result; // -0.0625
result -= n; // -0.0625 - 7.0 == -7.0625
boolean b = (result == -m); // true
boolean bb = (m < n); // false
// do not use increment and decrement operators
result = Fixed32.toFP(2);
++result; // WRONG! result will NOT be 3
result = Fixed32.toFP(2);
result += Fixed32.toFP(1); // Correct: result will be 3
// Use * and / when multiplying or dividing by an integer scalar
// Use mul to multiply two fixed-point numbers
// Use div to divide two fixed-point numbers
m = Fixed32.tenThouToFP(12500); // 1.25
m *= 3; // OK: 1.25 * 3 == 3.75
m /= 2; // OK: 3.75 / 2 == 1.875
m = Fixed32.mul(m, Fixed32.tenThouToFP(15000)); // 1.875 * 1.5000 == 2.8125
m = Fixed32.div(m, m); // 2.8125 / 2.8125 == 1.0
// mul, div, sqrt, sind, cosd, tand, and atand2
// all work with 16.16 fixed-point numbers
m = Fixed32.tenThouToFP(172500); // 17.2500
n = Fixed32.sqrt(m); // sqrt(17.25)
n = Fixed32.sind(m); // sine of 17.25 degrees
n = Fixed32.cosd(m); // cosine of 17.25 degrees
result = Fixed32.atand2(-m, -m); // -135.0 degrees in fixed-point
}
}
Next topic: OpenVG
Previous topic: Code sample: Loading a 3-D perspective projection matrix