JDK-4950948 : loop statements with double-type index, can ends at incorrect index.
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 1.4.2,5.0
  • Priority: P3
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_2000,windows_xp
  • CPU: x86
  • Submitted: 2003-11-07
  • Updated: 2005-05-13
  • Resolved: 2003-11-08
Related Reports
Relates :  
Relates :  
Relates :  
Description

Name: gm110360			Date: 11/07/2003


FULL PRODUCT VERSION :
java version "1.4.1_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-b01)
Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed mode)

A DESCRIPTION OF THE PROBLEM :
look the source and result.

while() and probably do...while()
produces same results.

EXPECTED VERSUS ACTUAL BEHAVIOR :
----------------------------------------
result:

 0.70
 0.80
 0.90
 1.00

but, if the initial value becomes 0.8 ,

 0.80
 0.90
---------------------------------------

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
import java.text.* ;

class Test
{
	static NumberFormat f = NumberFormat.getNumberInstance() ;
	static
	{
		( (DecimalFormat)f ).applyPattern( " #0.00;-" ) ;
	}

	public static void main( String[] param )
	{
		for( double a=0.7 ; a < 1 ; a += 0.1 )
		{
			System.out.println( f.format(a)  ) ;
		}
	}
}
---------- END SOURCE ----------
(Incident Review ID: 178890) 
======================================================================

Comments
EVALUATION This is not a bug, the floating-point computation is occuring as exepcted. Java's float and double arithmetic is binary; in general base 10 fractions like 0.1 do not have terminating binary representations. Therefore, the assignment double a=0.7 *cannot* assign a value exactly equal to "0.7" (or "0.8") to a. Therefore, it is not reasonable to expect the sum of quanities not exactly equal to 0.7, 0.8, or 0.1 to sum exactly to 1, the sum will be a little more or a little less. Any imprecision in the intended sum if further hidden by use of the NumberFormat. See "What Everybody Using the Java(TM) Programming Language Should Know About Floating-Point Arithmetic" http://java.sun.com/people/darcy/ for a detailed discussion of these issues. Similar to bugs 4430070, 4497156, 4421899. ###@###.### 2003-11-07 If exact decimal arithmetic is desired, use java.math.BigDecimal. ###@###.### 2003-11-07
07-11-2003