I want a function that creates an array of increasing floats. I run into problems when the incremenent cannot be represented precisely in binary. An example in an increment of 0.1, whose binary representation is infinitely repeating.
var incrementalArray = function(start, end, step) {
var arr = [];
for (var i = start; i <= end; i += step) {
// 0.1 cannot be represented precisely in binary
// not rounding i will cause weird numbers like 0.99999999
if (step === 0.1) {
arr.push(i.toFixed(1));
} else {
arr.push(i);
}
}
return arr;
};
There are two problems with this implementation. A) It only covers the case of having an increment of 0.1. Aren't there numerous other magic numbers that have repeating binary representation? B) The returned array does not include the end value when the increment is 0.1. However, it does include the end value when the increment is otherwise, making this function unpredictable.
incrementalArray(0.0, 3.0, 0.1);
// [0.0, 0.1, 0.2, .... 2.8, 2.9]
incrementalArray(2,10,2);
// [2, 4, 6, 8, 10]
How can this function work for all special increments and be predictable?