Wiki Markup |
---|
The Java language provides two primitive types, {{float}} and {{double}}, which "are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in _IEEE Standard for Binary Floating-Point Arithmetic_, ANSI/IEEE Standard 754-1985 (IEEE, New York)" (\[[JLSIEEE 2005754|AA. Bibliography#JLSBibliography#IEEE 754 052006]\], [Section 4.2.3|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3], "Floating-Point Types, Formats, and Values"). Each of the floating point types has a fixed, limited number of mantissa bits. Consequently, it is impossible to precisely represent any irrational number (for example, pi). Further, because these types use a binary mantissa, they cannot precisely represent many finite decimal numbers, such as 1/10, because these numbers have repeating binary representations. |
Wiki Markup |
---|
Avoid using the primitive floating point types when precise computation is necessary. Avoid, them especially when performing currency calculations. Instead, consider alternative representations that are able to completely represent the necessary values. Whatever representation you choose, you must carefully and methodically estimate the maximum cumulative error of the computations to ensure that the resulting error is within acceptable tolerances. Consider using numerical analysis to properly understand the problem. See \[[Goldberg 1991|AA. Bibliography#Goldberg 91]\] for an introduction to thesethis issuestopic. |
Noncompliant Code Example
...
Code Block |
---|
A dollar less 7 dimes is $0.3 |
Risk Assessment
Using a representation other than floating point can allow for more representation can result in a loss of precision and accuracy for critical arithmeticwhen precise computation is required.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
NUM00-J | low | probable | high | P2 | L3 |
...
Wiki Markup |
---|
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 48: Avoid {{float}} and {{double}} if exact answers are required
\[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 2: Time for a Change
\[[Goldberg 1991|AA. Bibliography#Goldberg 91]\]
\[[IEEE 754|AA. Bibliography#IEEE 754 2006]\]
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 4.2.3|http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.2.3], "Floating-Point Types, Formats, and Values" |
...