-1

Why out heap of memory, why last item in array don't step + 0.1?

const array = [];
const step = 0.1;
do {
    const item = array[array.length - 1] ? array[array.length - 1] : 0;
    array.push(item + step);
} while (array[array.length - 1] !== 100);

1 Answers1

1

Use less-than instead of not-equal-to e.g. while (array[array.length - 1] < 100), because you will not get EXACTLY 100, due to the nature of floating-point arithmetic.

See the output from the program below.

console.log(generateSequence(0, 100, 0.1));

function generateSequence(start, end, step) {
  let result = [];
  do {
    const prev = result[result.length - 1] ? result[result.length - 1] : 0;
    result.push(prev + step);
  } while (result[result.length - 1] < 100);
  return result;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Alternatively

You can increase the magnitude of the number, floor it, then divide it.

As you can see it works for multiple precisions.

console.log(generateSequence(0, 100, 1).join(', '));
console.log(generateSequence(0, 100, 10).join(', '));
console.log(generateSequence(0, 100, 0.1).join(', '));
console.log(generateSequence(0, 100, 0.025).join(', '));

function generateSequence(start, end, step) {
  let result = [],
      trueEnd = end / step,
      precision = step < 1 ? 1 / step : 1,
      p2 = Math.pow(precision, 2);
  for (let i = 0; i < trueEnd; i++) {
    result.push(Math.floor(i * precision) / p2);
  }
  return result;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132