Java Glossary : division

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : D words : division.

division
There are two kinds of division in Java, integer and floating point. They both use the / operator to ensure you will get them confused. It depends on whether the operands surrounding it are int/long or float/double which form is used. Integer division always gives an integer result, no fraction. Floating point division gives a fractional answer as accurate as IEEE format allows.

// sample divisions
int i = 7;
int j = 2;
int k = i / j; // gives 3
double d = (double) i / ( double) j; // gives 3.5
double oops = (double) ( i / j ); // gives 3.0
double shortcut = ((double) i ) / j; // gives 3.5, j is promoted to double automatically.
double surprise = 1.0d / 10.0d; // gives approximately 0.1.
// 0.1 is a binary repeater fraction.

Floating point division always seems to be a wee bit off from what you would expect. That is because many common decimal fractions are repeaters when expressed in binary that Java uses internally.

In Java you take the remainder with the % operator. In Java, the sign of the remainder follows the dividend, not the divisor.

Be especially careful when corralling random numbers into a smaller range with the modulus operator. Java division does have the Euclidean property. When you multiply the quotient by the divisor and add the remainder you get back to the dividend. Java division is truncated division.

Floored Division

Floored division is what you normally want when trying to figure out which bin an item belongs in. You can compute floored division as:

(dividend >= 0) ? (dividend / divisor) : ( (dividend - divisor + 1 ) / divisor );

Covered Quotient

For computing how many fixed-size bins you need to contain N items, you want ceiled division, also known as the covered quotient. You can compute the covered quotient as:

(dividend >= 0) ? ( (dividend + divisor - 1 ) / divisor) : (dividend / divisor );


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 5436.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/division.html J:\mindprod\jgloss\division.html