• Post Reply Bookmark Topic Watch Topic
  • New Topic

Looping through fractional values using for?  RSS feed

 
Jon Camilleri
Ranch Hand
Posts: 664
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A replacement for the loop that you posted:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!