/home/wpollock1/public_html/Java/TestSum.java
// From Liang's "Intro to Java Programming", 11th ed, p. 180)
// This demo shows some of the errors caused by using floats and doubles
// in loops.
//
// Written 3/2017 by Wayne Pollock, Tampa Florida USA
public class TestSum {
public static void main ( String[] args ) {
System.out.println( "Sum 0.01..1.0 using floats "
+ "(should result in 50.50):" );
floatTest();
System.out.println( "\nSum 0.01..1.0 using doubles, the wrong way:" );
doubleTestWrongWay();
System.out.println( "\nSum 0.01..1.0 using doubles, a better way:" );
doubleTestBetterWay();
System.out.println( "\nSum 0.01..1.0 using ints and divide at the end, "
+ "the best way:" );
intTest();
}
// This should only produce a small error:
static void floatTest () {
float sum = 0.0f;
// Add 0.01 .. 1.0 to sum:
for ( float i = 0.01f; i <= 1.0f; i += 0.01f )
sum += i;
System.out.println( " Result: " + sum );
}
// This produces a large error! The reason is that the loop executes
// one less iteration; the final iteration has i at 1.00...something,
// and since that is greater than 1.0, the loop terminates early:
static void doubleTestWrongWay () {
double sum = 0.0;
for ( double i = 0.01; i <= 1.0; i += 0.01 )
sum += i;
System.out.println( " Result: " + sum );
}
// Just don't use floating point as loop control variables:
static void doubleTestBetterWay () {
double sum = 0.0, increment = 0.01;
for ( int i = 1; i <= 100; i += 1 ) {
sum += increment;
increment += 0.01;
}
System.out.println( " Result: " + sum );
}
// Best way: don't use floating point at all:
static void intTest () {
int sum = 0;
for (int i = 1; i <= 100; i += 1 )
sum += i;
System.out.println( " Result: " + sum / 100.0 );
}
}