如何在java中生成两个值之间的序列? [英] How to generate a sequence between two values in java?
问题描述
我拥有的两个值是:
firstval=200.000
Secondval=399.999,
我必须生成一个数字,以便当整数部分的第一个小数部分应该增加到 999
时,接下来应该增加整数部分,然后小数部分重置为 000
并开始为新数字递增.这一直发生到 399
.喜欢
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"
200.001,200.002.....200.999,201.000,201.002....399.998,399.999"
推荐答案
Java 8 Stream API 有一个很好的方法来获取所需的数组
There is a nice way to get required array with Java 8 Stream API
(1) 使用双增量
double[] sequence = DoubleStream.iterate(200.0, d -> d + 0.001).limit((int) (1 + (399.999 - 200.0) / 0.001)).toArray();
请注意,对大量双打求和可能会产生一些错误,例如在我的笔记本电脑上,序列中的最后一个数字是 399.998999999686227
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) 更好的方法是生成整数流并将其映射到双精度:
(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
这篇关于如何在java中生成两个值之间的序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!