posted 6 years ago

"CAUTION: Be careful about testing for equality of floating-point numbers in loops, for example:

Source: Core Java Vol I Fundamentals 8th Edition (http://www.amazon.com/Core-Java-TM-I-Fundamentals-8th/dp/0132354764). Pg. 82.

How would you suggest coding a loop that increments in decimal points? Do you know of any practical examples when you had to do this?

Once I had to code a graph in VB, and, I remember using a for loop to decrement a counter variable by fractions of 1 to try to find solutions (programmatically)

for an algebraic equation y = Ax^3 + Bx^2 + Cx + D where A, B, C, and, D were values provided by the user, however, my solution did not quite work as

expected and I got a few marks less from the school assignment.

Source: Core Java Vol I Fundamentals 8th Edition (http://www.amazon.com/Core-Java-TM-I-Fundamentals-8th/dp/0132354764). Pg. 82.

How would you suggest coding a loop that increments in decimal points? Do you know of any practical examples when you had to do this?

Once I had to code a graph in VB, and, I remember using a for loop to decrement a counter variable by fractions of 1 to try to find solutions (programmatically)

for an algebraic equation y = Ax^3 + Bx^2 + Cx + D where A, B, C, and, D were values provided by the user, however, my solution did not quite work as

expected and I got a few marks less from the school assignment.

Jon

posted 6 years ago

- 1

If you need the precision to be accurate then BigDecimal is often the best choice. Just keep in mind to not initialize it using doubles, because the rounding problem* may have already occurred.

On other occasions using int / long to represent some smaller unit (like using long for cents instead of double for dollars) is a good alternative.

* Check out #20 from our Java Beginners Faq.

On other occasions using int / long to represent some smaller unit (like using long for cents instead of double for dollars) is a good alternative.

* Check out #20 from our Java Beginners Faq.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions