Java Reference
In-Depth Information
Compliant Solution (Floating-Point Literal)
The following compliant solution performs the multiplication and division operations on
floating-point values, avoiding both the truncation and the overflow seen in the noncom-
pliant code example. In every operation, at least one of the operands is of a floating-point
type, forcing floating-point multiplication and division, and avoiding truncation and over-
flow:
Click here to view code image
short a = 533;
int b = 6789;
long c = 4664382371590123456L;
float d = a / 7.0f; // d is 76.14286
double e = b / 30.; // e is 226.3
double f = (double)c * 2; // f is 9.328764743180247E18
Another compliant solution is to eliminate the truncation and overflow errors by storing
the integers in the floating-point variables before performing the arithmetic operations:
Click here to view code image
short a = 533;
int b = 6789;
long c = 4664382371590123456L;
float d = a;
double e = b;
double f = c;
d /= 7; // d is 76.14286
e /= 30; // e is 226.3
f *= 2; // f is 9.328764743180247E18
As in the previous compliant solution, this practice ensures that at least one of the op-
erands of each operation is a floating-point number. Consequently, the operations are per-
formed on floating-point values.
In both compliant solutions, the original value of c cannot be represented exactly as a
double . The representation of type double has only 48 mantissa bits, but a precise rep-
resentation of the value of c would require 56 mantissa bits. Consequently, the value of
Search WWH ::




Custom Search