Java Reference
In-Depth Information
mathematical calculations beyond integer calculations. As a substitute for the missing floating-point
arithmetic, Onno Hommes created a library called MathFP providing 32-bit fixed-point integer math
functions. The MathFP library and the corresponding documentation can be downloaded at
http://www.jscience.net .
To perform calculations in the MathFP format, you need to convert an integer or a string representing a
floating-point value to the MathFP format. Those conversions are performed using the static methods
of the class MathFP given in Table 10.4 .
Table 10 .4. Conversion Methods to the MathFP Format
Method Name
Description
toFP(int l)
Converts a normal Java int to a fixed-point integer.
toFP(String s)
Converts a string input to a fixed-point integer.
The following code snippet shows the conversion on two small examples:
// conversion of an integer to a MathFP integer
int mathFPInt1 = MathFP.toFP (1234);
// conversion of a String to a MathFP integer
int mathFPInt2 = MathFP.toFP("12.9881");
After successful conversion to the MathFP format, you are able to perform mathematical calculations
using the methods supported in the MathFP library. The MathFP functionality ranges from simple
addition, subtraction, multiplication, and division to powerful operations such as sine, cosine, and
tangent of radian values.
To add or subtract two MathFP integers, you can use the methods add() and sub() or use the plus
( + ) or minus ( - ) operators directly:
// adding two MathFP integers using methods
int mathFPResult1 = MathFP.add(mathFPInt1, mathFPInt2);
// adding two MathFP integers using operators
int mathFPResult2 = mathFPInt1 + mathFPInt2;
// subtracting two MathFP integers using methods
int mathFPResult3 = MathFP.sub (mathFPInt1, mathFPInt2);
// subtracting two MathFP integers using operators
int mathFPResult4 = mathFPInt1 - mathFPInt2;
Simplifying the code by using the standard int operators is only possible for the add() and sub()
methods. You can convert the result back to a Java integer or String type (for example, to display the
result) using one of the three methods listed in Table 10.5 .
Table 10.5. Conversion Methods from the MathFP Format Back to the Java Standard
Types
Method Name
Description
toInt(int x)
Converts a MathFP integer back to a normal integer.
toString(int x)
Returns the MathFP integer as String .
toString(int x, int d)
Returns the MathFP integer as String with rounding.
The following snippet of code demonstrates how the result of a particular MathFP operation can be
converted to a String :
 
 
 
Search WWH ::




Custom Search