19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

154 Chapter 4 Loops<br />

VideoNote<br />

Minimize numeric errors<br />

loop<br />

Key<br />

Point<br />

4.7 Minimizing Numeric Errors<br />

Using floating-point numbers in the loop continuation condition may cause numeric errors.<br />

Numeric errors involving floating-point numbers are inevitable. This section discusses how <strong>to</strong><br />

minimize such errors through an example.<br />

Listing 4.8 presents an example summing a series that starts with 0.01 and ends with 1.0.<br />

The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03, and so on.<br />

LISTING 4.8<br />

TestSum.java<br />

1 public class TestSum {<br />

2 public static void main(String[] args) {<br />

3 // Initialize sum<br />

4 float sum = 0;<br />

5<br />

6 // Add 0.01, 0.02, ..., 0.99, 1 <strong>to</strong> sum<br />

7 for (float i = 0.01f; i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!