On the face of it your version looks like it should work. However, I suspect you are running into a problem that is inherent in all computations that use float
and double
: floating point types are inexact1.
See: Is floating point math broken?
(The answer is: No ... but it doesn't work how you think it does.)
Anyhow, with code like this:
for (double i = lower; i <= upper; i = i + 0.1) {
System.out.println(i);
}
you might find that the values printed are not exactly what you expect. Indeed, the last value (upper
or thereabouts) may not be printed. The root cause is floating point imprecision (as explained in the above Q&A).
If you want exact values to be printed all of the time you will need to use BigDecimal
to represent the numbers and perform the arithmetic.
1 - This is not a Java specific problem. You will see the same effect with any programming language that uses base-2 floating point representations for numbers. Most modern computers have IEEE 754 compliant floating point arithmetic support in hardware, and most languages make use of this your their floating point types.