How to generate a sequence between two values in java?


Keywords:java 


Question: 

The two values that i have are:

firstval=200.000 
Secondval=399.999,

I have to generate a numbers such that when the first decimal part should get incremented till 999 for the integral part, next the integral part should be incremented and then decimal part resets to 000 and starts incrementing for the new number . And this happens till 399. Like

200.001,200.002.....200.999,201.000,201.002....399.998,399.999"


3 Answers: 

There is a nice way to get required array with Java 8 Stream API

(1) Use double incrementation

 double[] sequence = DoubleStream.iterate(200.0, d -> d + 0.001).limit((int) (1 + (399.999 - 200.0) / 0.001)).toArray();

Note, that summing up lots of doubles will likely give some error, for example on my laptop the last number in the sequence is 399.99899999686227

(2) Better way is to generate integer stream and map it to doubles:

 double[] sequence = IntStream.range(200000, 400000).mapToDouble( i -> i * 0.001).toArray();

In this case no error from adding multiple doubles will be accumulated



double start = 200.0;
double end = 399.999;
double increment = 0.001;

for (double v = start; v < end + increment / 2; v += increment) {
    System.out.printf("%.3f\n", v);
}


Here's another way to do it:

public static void counterGenerator(double start, double end) {
    DecimalFormat counterInDecimalFormat = new DecimalFormat("0.000");
    String counterInString = counterInDecimalFormat.format(start);
    System.out.println(counterInString); // This is the counter in String format.
    double counter = Double.parseDouble(counterInString);
    if (counter < end)
        counterGenerator(start + 0.001, end);
    return;
}

In the above example, you have your counter in String format in the variable called counterInString

But you need not worry about the problems associated with incrementing a Double which is actual residing in a String variable. In the code, you can see the incrementing task is being done by a double counter which gets convert back to String by using the DecimalFormat class.

Here keeping your counter as a String helps you to retain the 0s after decimal in numbers like 200.000.

Hope it helps!