How to generate the sequence between 0.1 to 46.61 with interval 0.1

Viewed 78

Hi i want to generate every possible interval from 0.1 to 46.61

my expected result must look like this

0.1 0.2 0.3 ... ... 46.1 46.2 46.3 46.4 46.5 46.6

Here is what i have tried but not working correctly

let wholeDuration = 46.61;

let interval = 0.1, res = [];

for(let i = 0; i < wholeDuration; i++){
   res.push(interval * i)
}

console.log(res);

4 Answers

Too bad, this is how machine floating precision operations work. However, there are some workarounds that can produce result closer to "familiar". One of thos is to use integer as counter and divide by 10 (this works in your case because 1 is excatly 10 times your interval value)

let wholeDuration = 46.61, interval = 0.1, res = [];
let divisor = 10;
let limit = 466.1; // wholeDuration * divisor;
let step = 1; // interval * divisor

for(let i = 0; i < limit; i += step){
   res.push(i / divisor);
}

console.log(res);

When you know the length of your future array is better to use new Array instead of loops.

See my example below:

let pointFrom = 0.1;
let pointTo = 46.6;
let multiplier = 0.1;

let arr = new Array(((pointTo - pointFrom) / 0.1) + 1).fill(null).map((_, x) => parseFloat(((x * multiplier) + pointFrom).toFixed(1)));
console.log(arr, arr.length)

Normally JavaScript knows just floating point arithmetic. But some JavaScript engines have optimizations for integer arithmetic. So just use integers for the incrementation.

let res = [];

for (let i = 1; i < 467; i++) {
   res.push (i/10)
}

console.log (res);

Just replace your numbers in a for loop:

const arr = [];
for (let i = 0.1; i < 46.7; i += 0.1) {
  arr.push(i.toFixed(1))
}
console.log(arr);

Or it's possible to use generators too:

function* seq() {
  for (let i = 0.1; i < 46.7; i += 0.1) {
    yield i.toFixed(1);
  }
}

const arr = [...seq()];

console.log(arr)

// Also
// for (const point of seq()) {
//   console.log('point', point);
// }

Related