Java Reference
In-Depth Information
Taking a Fraction of an Integer Without Using Floating Point
Problem
You want to multiply an integer by a fraction without converting the fraction to a floating-
point number.
Solution
Multiply the integer by the numerator and divide by the denominator.
This technique should be used only when efficiency is more important than clarity because it
tends to detract from the readability—and therefore the maintainability—of your code.
Discussion
Because integers and floating-point numbers are stored differently, it may sometimes be de-
sirable and feasible, for efficiency purposes, to multiply an integer by a fractional value
without converting the values to floating point and back, and without requiring a “cast”:
public
public class
class FractMult
FractMult {
public
public static
static void
void main ( String [] u ) {
double
double d1 = 0.666 * 5 ; // fast but obscure and inaccurate: convert
System . out . println ( d1 ); // 2/3 to 0.666 in programmer's head
double
double d2 = 2 / 3 * 5 ;
// wrong answer - 2/3 == 0, 0*5 = 0
System . out . println ( d2 );
double
double d3 = 2 d / 3 d * 5 ; // "normal"
System . out . println ( d3 );
double
double d4 = ( 2 * 5 )/ 3 d ;
// one step done as integers, almost same answer
System . out . println ( d4 );
int
int i5 = 2 * 5 / 3 ;
// fast, approximate integer answer
System . out . println ( i5 );
}
}
Running it looks like this:
Search WWH ::




Custom Search