实际上,我很惊讶我无法在这里找到答案,尽管也许我只是使用了错误的搜索词或其他内容。我能找到的最接近的是this,但是他们询问如何生成double具有特定步长的s 的特定范围,答案也是如此。我需要一些可以生成具有任意开始,结束和步长大小的数字的东西。
我算起来也有是在图书馆这样的一些方法已经某处,但如果让我无法轻松地找到它(再次,也许我只是用错了搜索词或某事)。因此,这是我在过去几分钟内自行完成的操作:
import java.lang.Math;
import java.util.List;
import java.util.ArrayList;
public class DoubleSequenceGenerator {
     /**
     * Generates a List of Double values beginning with `start` and ending with
     * the last step from `start` which includes the provided `end` value.
     **/
    public static List<Double> generateSequence(double start, double end, double step) {
        Double numValues = (end-start)/step + 1.0;
        List<Double> sequence = new ArrayList<Double>(numValues.intValue());
        sequence.add(start);
        for (int i=1; i < numValues; i++) {
          sequence.add(start + step*i);
        }
        return sequence;
    }
    /**
     * Generates a List of Double values beginning with `start` and ending with
     * the last step from `start` which includes the provided `end` value.
     * 
     * Each number in the sequence is rounded to the precision of the `step`
     * value. For instance, if step=0.025, values will round to the nearest
     * thousandth value (0.001).
     **/
    public static List<Double> generateSequenceRounded(double start, double end, double step) {
        if (step != Math.floor(step)) {
            Double numValues = (end-start)/step + 1.0;
            List<Double> sequence = new ArrayList<Double>(numValues.intValue());
            double fraction = step - Math.floor(step);
            double mult = 10;
            while (mult*fraction < 1.0) {
                mult *= 10;
            }
            sequence.add(start);
            for (int i=1; i < numValues; i++) {
              sequence.add(Math.round(mult*(start + step*i))/mult);
            }
            return sequence;
        }
        return generateSequence(start, end, step);
    }
}
这些方法运行一个简单的循环,将乘以step序列索引,然后加上start偏移量。这样可以减轻由于连续递增而产生的复合浮点错误(例如,step在每次迭代中将都添加到变量中)。
我generateSequenceRounded为步长分数可能导致明显的浮点错误的情况添加了该方法。它确实需要更多的算术运算,因此在对性能非常敏感的情况下(例如我们的情况),在不需要舍入时可以选择使用更简单的方法,这是很好的选择。我怀疑在大多数一般用例中,舍入开销可以忽略不计。
注意,我有意排除的逻辑,用于处理“异常”的参数,如Infinity,NaN,start> end,或负step为简单起见尺寸和期望集中于手头的问题。
这是一些示例用法和相应的输出:
System.out.println(DoubleSequenceGenerator.generateSequence(0.0, 2.0, 0.2))
System.out.println(DoubleSequenceGenerator.generateSequenceRounded(0.0, 2.0, 0.2));
System.out.println(DoubleSequenceGenerator.generateSequence(0.0, 102.0, 10.2));
System.out.println(DoubleSequenceGenerator.generateSequenceRounded(0.0, 102.0, 10.2));
[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0, 1.2000000000000002, 1.4000000000000001, 1.6, 1.8, 2.0]
[0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
[0.0, 10.2, 20.4, 30.599999999999998, 40.8, 51.0, 61.199999999999996, 71.39999999999999, 81.6, 91.8, 102.0]
[0.0, 10.2, 20.4, 30.6, 40.8, 51.0, 61.2, 71.4, 81.6, 91.8, 102.0]
是否已经存在提供这种功能的现有库?
如果没有,我的方法是否有任何问题?
有谁有更好的方法吗?