-2

I'm getting two values like a=2.7 (It can be anything in decimal for e.g 2.007 & ..) b=3.5 (It can be anything in decimal for e.g 3.007 & ..)

I want to extract all value between 2.7 to 3.5 i.e. 2.7, 2.8, 2.9 ........ 3.5

The thing that I have tried is

for (double i = lower; i <= upper; i=i+0.1) {
    Storing i value;
            }

Where lower is starting decimal and upper is ending decimal value

How can I achieve this with for loop or any other method ? Note : The value can be 2.7 OR 2.00007 as well

2 Answers2

0

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

Try by rounding off because up to one decimal point, this will work for you.

for (double i = lower; i <= upper; i += 0.1) 
        System.out.printf("%.1f\n",i); 

You can find more about the problem without rounding off Why does adding 0.1 multiple times remain lossless?

Sumit Singh
  • 487
  • 5
  • 19